gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:23:08 26 4
gpt4 key购买 nike

我是编码新手,遇到了以下错误。

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() */

关于c++ - 在比较二进制数字输入的字符时抛出 'std::out_of_range 的实例后终止调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65121003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com