C++当我成功地定制另一个字符串时,我无法定制一个字符串
C++ I cannot cout one string while i successfully cout an another 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]=' ';
cout << endl << bin << " in decimal is: " << dec << endl;
}
下面是运行结果:
输入二进制数字:10101010
10101010十进制为:
在"是"之后应该有我的十进制数;然而什么都没有。我试着单独定制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;
@SebastianK已经解决了std::string
长度为零的问题。我想添加它而不是以下内容:
dec[2]=temp_a+48;
dec[1]=temp_b+48;
dec[0]=temp+48;
dec[3]=' ';
您可以使用push_back()
成员函数将字符附加到空的std::string
dec.push_back(temp + '0');
dec.push_back(temp_b + '0');
dec.push_back(temp_a + '0');
请注意,您不需要以NULL终止std::string
,我使用了字符文字'0'
而不是ASCII值48,因为我认为它更清晰。
注意:这只是一个带有代码的注释,而不是实际的答案。
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] = ' ';
cout << endl << bin << " in decimal is: " << dec << endl;
}