使用C ++。我的代码要求用户输入字符串,以二进制形式将该字符串打印回来,提示他们输入一些二进制文件,然后将该二进制文件转换回字符串。在测试代码时,我输入一个像“bed”这样的字符串,然后重新输入二进制文件。当它将二进制文件转换回来时,我将以“bbb”结束,因此它返回前8位* 8的段。
有关修复此问题的任何建议吗?看起来我的变量开始回到0.我已经尝试过(int a = z; .....)并且这只打印前8位(“bed” - > binary - >“ b“)
我的代码是:
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
using namespace std;
int main()
{
string stuff;
cout << "type some stuff :" << endl;
getline(cin, stuff);
int convert = 0,
toconvert = 0;
for(int i = 0; i < stuff.length(); i++)
{
cout << bitset<8>(stuff.at(i));
}
string retype;
cout << "type in some sweet binary:" << endl;
getline(cin, retype);
char mycharacter;
for(int z = 0; z < retype.length(); z += 8 )
{
for(int a = 0; a < retype.length(); a++)
{
if (retype.at(a) == '1' )
{
convert = (int)pow( 2,( 7- a));
toconvert = toconvert + convert;
}
else if (retype.at(a) == '0')
{
toconvert = toconvert + 0;
}
else
{
cout << "you did not type binary, try again" << endl;
}
}
mycharacter = char(toconvert);
cout << mycharacter;
toconvert = 0;
}
cout << " " << endl;
return 0;
}