2013-05-03 26 views
0

所以我的實驗室基本上是從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; 
} 
+0

你沒有分配任何字符串。他們只是懸掛指針,不指向有效的內存位置。另外,這是C++;使用'std :: string' – 2013-05-03 19:56:03

+0

我建議你看一下http://www.youtube.com/watch?v=i49_SNt4yfk,然後用std :: string代替char *。 – PlasmaHH 2013-05-03 19:56:17

回答

2

ASTRING和bString不分配。

char* aString = new char[255]; 
char* bString = new char[255]; 

確保在完成後刪除這些指針。

delete[] aString; 
delete[] bString; 
aString = 0x0; 
bString = 0x0; 

如果你不需要使用的char *用於輸入,您可以使用std::string(所以你不必擔心您的輸入分配足夠的空間),然後與底層工作使用c_str()的std :: string的char緩衝區。

例子:

std::string aString; 
std::cin >> aString; 
const char* buffer = aString.c_str(); 
+0

沒有提及'delete'? – 2013-05-03 20:00:29

+0

更新了我的回答:) – Ryan 2013-05-03 20:02:47

+0

注意:'delete []'在這裏特別重要,注意不要簡單地用'delete'! – eriknelson 2013-05-03 20:11:27

0

添加的語句,如aString = new char[80];你第一次嘗試somethiong讀入該變量之前。

+0

謝謝你的幫助! – 2013-05-03 20:33:32