Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error: terminate called after throwing an instance of 'std::out_of_range

When I typed this code

#include <iostream>
#include <string>

class binary
{
    std::string s;

public:
    void read();
    void check_format();
};
void binary::read()
{
    std::cout << "Enter a number\n";
    std::cin >> s;
}
void binary ::check_format()
{
    for (int i = 1; i <= s.length(); i++)
    {
        if (s.at(i) != '0' && s.at(i) != '1')
        {
            std::cout << "Incorrect format\n";
            exit(0);
        }
    }
};
int main()
{
    binary num;
    num.read();
    num.check_format();
    return 0;
}

I was getting the correct output for the oneswith no ‘1’ and ‘0’ in them like 44, but for the numbers with ‘1’ and ‘0’ in them I got this error

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

Please help in fixing this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

C++ strings indexes are zero-based. That means if a string has a size of n. its indexes are from 0 to n - 1.

For example:

#include <iostream>
#include <string>

int main()
{
    std::string s {"Hello World!"} // s has a size of 12.
    std::cout << s.size() << '\n'; // as shown
    std::cout << s.at(0); << '\n' // print the first character, 'H'
    std::cout << s.at(11); << '\n' // print the last character, '!'
}

But you are looping from 1 to n. When i == n, s.at(i) become out-of-bounds, and because of that, it throws an std::out_of_range error

Change your loop to:

void binary::check_format()
{
    for (int i = 0; i < s.length(); i++)
    {
        if (s[i] != '0' && s[i] != '1') // at() does bounds checking, [] is faster
        {
            std::cout << "Incorrect format\n";
            exit(0);
        }
    }
}

Or better:

void binary::check_format()
{
    for(const auto &i : s)
    {
        if (i != '0' && i != '1')
        {
            std::cout << "Incorrect format\n";
            exit(0);
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading