所以我的實驗室基本上是從cin中取出一個字符串,將它分成組件(分成不同的字符),然後使用按位運算符做所有字符的分量總和。最後,打印出結果。這是我的。按位分量總和的分段錯誤
輸入第一個字符串後,我得到一個分段錯誤。
現在運行沒有segFaults,但我得到結果= 0,aInt = 0,bInt = 0. 不知道爲什麼? 我打一個招呼=和b =世界
using namespace std;
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int main()
{
string a, b;
char *aStopstring, *bStopstring;
unsigned long aInt, bInt;
cout<<"Please enter a string: "<<endl;
cin>> a;
const char* aString = a.c_str();
cout<<"Please enter another string: "<<endl;
cin>> b;
const char* bString = b.c_str();
aInt = strtoul(aString, &aStopstring, 2);
bInt = strtoul(bString, &bStopstring, 2);
cout<<aInt<< " " << bInt<<endl;
unsigned int c = aInt&bInt;
unsigned int d = aInt^bInt;
c = c>>1;
unsigned int result = c^d;
cout<<"The sum is: "<< (int)result <<endl;
return 1;
}
你沒有分配任何字符串。他們只是懸掛指針,不指向有效的內存位置。另外,這是C++;使用'std :: string' – 2013-05-03 19:56:03
我建議你看一下http://www.youtube.com/watch?v=i49_SNt4yfk,然後用std :: string代替char *。 – PlasmaHH 2013-05-03 19:56:17