所以我的实验室基本上是从 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;
}
最佳答案
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 的底层字符缓冲区。
例子:
std::string aString;
std::cin >> aString;
const char* buffer = aString.c_str();
关于c++ - 按位分量和中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16366561/