【发布时间】:2021-11-26 13:16:11
【问题描述】:
当我输入这段代码时
#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;
}
对于其中没有“1”和“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)
请帮忙解决这个问题。
【问题讨论】:
-
索引从零开始,一直到 size-1
-
您在输入代码时已经收到错误信息? :P 总之,在 C(和许多低级语言)中,第一个元素的索引为 0,最后一个(N 个元素)的索引为 N-1。
标签: c++