C++ 当我成功计算出另一个字符串时,我无法计算出一个字符串

标签 c++ string

我有一个很奇怪的问题。 我正在做的是尝试将字符串中的 8 位二进制数转换为十进制数(也是字符串) 在代码的末尾,我计算出二进制字符串和十进制字符串,但是当我运行时,我只成功看到了二进制字符串,但看不到十进制字符串...

这是我的代码:

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;


void bintodec(string bin);

int main()
{
    string bin="";
    bintodec(bin);
    return 0;
}

void bintodec(string bin)
{
    int temp;
    int temp_a;
    int temp_b;
    string dec;

    cout << "Enter the binary number: ";
    cin >> bin;

    temp = 128*(bin[0]-48) + 64*(bin[1]-48) + 32*(bin[2]-48) + 16*(bin[3]-48) + 8*(bin[4]-48) + 4*(bin[5]-48) + 2*(bin[6]-48) + (bin[7]-48);
    temp_a = temp%10;
    temp = (temp - temp_a) / 10;
    temp_b = temp%10;
    temp = (temp - temp_b) / 10;

    dec[2]=temp_a+48;
    dec[1]=temp_b+48;
    dec[0]=temp+48;
    dec[3]='\0';

    cout << endl << bin << " in decimal is: " << dec << endl;
}

这是运行结果:

Enter the binary number: 10101010

10101010 in decimal is:

“is”后面应该是我的十进制数;然而什么也没有。我尝试分别计算 dec[0] dec[1] 和 dec[2] 并且它有效,但是当我计算整个 dec 时,我每次都失败......

谁能告诉我我的问题出在哪里?我认为我的代码有问题,但我可以弄清楚......

最佳答案

dec 的大小为零。但是您访问位置 0 到 3 的元素。 例如,您可以使用

创建初始化为适当大小的dec
string dec(4, ' '); // fill constructor, creates a string consisting of 4 spaces

而不是

string dec;

.

关于C++ 当我成功计算出另一个字符串时,我无法计算出一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18537630/

相关文章:

c++ - 即使条件不成立,while 循环也会运行

c++ - 使用函数的返回类型和参数类型作为模板类型

javascript - 如何从返回的 JSON 字符串中提取某些数据?

c++ - 从蓝牙地址读取 3 个字节?

c++ - OpenCV - 实现新描述符时的链接器错误 - 旋转不变 BRIEF

c++ - 控制台不打印我想要的字符,它打印一个 block

Java:如何分割字符串而忽略其他部分

php - 如何将 "Port O' brian 替换为 "Port O' Brian”?

c - fgets 读取比应有的更多的字符

python - 将字符串中的日期列表转换为 Python 中的月、日、年