错误:引发"std::out_of_range 实例后终止调用



当我键入此代码时

#include <iostream>
#include <string>
class binary
{
std::string s;
public:
void read();
void check_format();
};
void binary::read()
{
std::cout << "Enter a numbern";
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 formatn";
exit(0);
}
}
};
int main()
{
binary num;
num.read();
num.check_format();
return 0;
}

我得到了其中没有"1"one_answers"0"的数字(如44(的正确输出,但对于其中有"1"或"0"数字,我得到了这个错误

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

请帮忙解决这个问题。

C++字符串索引是从零开始的。这意味着如果一个字符串的大小为n。其索引为从CCD_ 2到CCD_。

例如:

#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, '!'
}

但是您正在从1循环到n。当i == ns.at(i)出界时,因此会抛出std::out_of_range错误

将循环更改为:

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 formatn";
exit(0);
}
}
}

或者更好:

void binary::check_format()
{
for(const auto &i : s)
{
if (i != '0' && i != '1')
{
std::cout << "Incorrect formatn";
exit(0);
}
}
}

最新更新