C ++当我成功地播放另一个字符串时,我无法播放一个字符串

时间:2013-08-30 16:32:55

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

这是运行结果:

  

输入二进制数:10101010

     

10101010(十进制)是:

在“是”之后

应该有我的十进制数;但是什么都没有。我试图单独决定dec [0] dec [1]和dec [2]并且它有效,但是当我整个十二月时,我每次都失败了......

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

3 个答案:

答案 0 :(得分:4)

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

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

而不是

string dec;

答案 1 :(得分:1)

@SebastianK已经解决了你的std::string长度为零的事实。我想补充一下而不是以下内容:

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

您可以使用std::string成员函数将追加字符添加到空push_back()

dec.push_back(temp + '0');
dec.push_back(temp_b + '0');
dec.push_back(temp_a + '0');

请注意,您不需要NULL终止std::string,我使用字符文字'0'而不是ASCII值48,因为我认为它更清楚。

答案 2 :(得分:0)

注意:这只是代码注释,而不是实际答案。

int main()
{
    string bin="";
    decode(bin);
}

void decode(string bin)
{
}

这会导致在进入“decode”时创建一个新字符串,并将“bin”的内容复制到它。解码结束时对decode :: bin所做的任何更改都将对main不可见。

您可以避免这种情况 - 称为“按值传递”,因为您传递的是“bin”而不是“bin”本身的值 - 使用“按引用传递”

void decode(string& bin)

但在您的代码中,您实际上似乎根本不需要传递“bin”。如果您在解码后需要在主体中使用“bin”,则可以考虑将其返回:

int main()
{
    string bin = decode();
}

string decode()
{
    string bin = "";

    ...

    return bin;
}

但是现在,只需从main中删除bin并使其成为解码中的局部变量。

void bintodec();

int main()
{
    bintodec();
    return 0;
}

void bintodec()
{
            std::string bin = "";
    cout << "Enter the binary number: ";
    cin >> bin;

    int 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);
    int temp_a = temp%10;
    temp = (temp - temp_a) / 10;
    int temp_b = temp%10;
    temp = (temp - temp_b) / 10;

            char dec[4] = "";
    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;
}