在比较二进制数输入的字符时抛出 'std::out_of_range 实例后调用的终止



我对编码很陌生,遇到了以下错误。

terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::at: __n (which is 6) >= this->size() (which is 6)
Aborted (core dumped)

以下代码为:

#include <iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
string  sa=to_string(a);
string sb=to_string(b);

int l=sa.length();
for(int i=0;i<l;i++)
{
if(sa.at(i)==sb.at(i))
{
cout<<0;
}
else
cout<<1;
}
}

这个问题的输入是

1010100
0100101

如有任何帮助,我们将不胜感激!

由于前导零,第二个输入读取为100101
试图访问1010100的字符数将超出其长度。

若要求解,请将两者读入字符串。

例如,如下所示(请注意,该代码仅演示了我提出的更改,它仍然容易受到100 10等不同长度输入的攻击,并存在其他缺点(:

string  sa,sb;
cin>>sa>>sb;
/* no to_string() */

正如另一个答案所说,您可以以字符串形式读入。

然而,给定两个整数a&b、 如果您希望将它们转换为具有固定长度的字符串(即,在数字前面填充0(,则可以使用iomanip和stringstream。

#include <sstream>
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int a=123,b=12345;
// sa is 000123
stringstream ss;
ss << setw(6) << setfill('0') << a;
string sa = ss.str();
// clear the string stream buffer
ss.str(string());
// sb is 012345
ss << setw(6) << setfill('0') << b;
string sb = ss.str();
std::cout << sa << ":" << sb << endl;
return 0;
}

最新更新