c++ - 按位分量和中的段错误

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

最佳答案

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/

相关文章:

C++ header 中包含哪些内容以及 CPP 文件中包含哪些内容?

java - contains方法如何匹配?

c - 如何在C中检查输入字符串的长度

C++ 程序在 gcc 的 SIGSEGV 期间不处理任何函数调用或 printf

c++ - 使用 SSE 指令的 openMP 程序中线程 > 4 的段错误

c++ - C++ 程序员的 C 陷阱和错误

c++ - OpenCV 在 warpAffine 期间保持背景透明

c++ - 如何确保 CMakeLists.txt 和 FindXXX.cmake 的编码风格一致

java - Java中的美元货币格式

c - 简单链表C代码段错误