简体   繁体   中英

Terminate called after throwing an instance of 'std::out_of_range when comparing characters of binary number input

I am pretty new to coding and encountered the following error.

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)

The code for the following was:

#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;
    }
}

The input for this problem was

1010100

0100101

Any help regarding this will be appreciated!

The second input is read 100101, because of the leading zero.
Trying to access as many characters as 1010100 has will go beyond its length.

To solve read both in as string.

Eg like the following (note that the code only demonstrates the change I propose, it is still vulnerable by differently long input like 100 10 and has other shortcomings):

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

As another answer says, you can read in as string.

However, given two integers a & b, if you want them to be converted into string with fixed length (ie, 0 padded in front of the numbers), you can use iomanip and 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM