按位分量和的分段错误

时间:2013-05-03 19:54:11

标签: c++ string segmentation-fault sum bit-manipulation

所以我的实验室基本上从cin中取出一个字符串,将它分成组件(进入各种字符),然后使用按位运算符对所有字符进行组件求和。最后,打印出结果。这就是我所拥有的。

输入第一个字符串后立即出现分段错误。

[编辑]现在运行没有segFaults,但我得到的结果= 0,aInt = 0,bInt = 0。 不明白为什么? 我键入了a = hello和b = world

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;
}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

在您第一次尝试将某些内容读入该变量之前,添加aString = new char[80];之类的语句。