-1

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.

bbahd
  • 49
  • 8

1 Answers1

0

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