【问题标题】:Error: terminate called after throwing an instance of 'std::out_of_range [duplicate]错误:在抛出 'std::out_of_range 的实例后调用终止 [重复]
【发布时间】: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++


【解决方案1】:

C++ 字符串索引是从零开始的。这意味着如果字符串的大小为n。它的索引是从0n - 1

例如:

#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 format\n";
            exit(0);
        }
    }
}

或者更好:

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

【讨论】:

  • 感谢大家的帮助,又学到了新东西。如果只有 1 和 0,您能否建议如何使其打印二进制格式正确
  • @user17373135 每个问题一个问题!
  • 好的,抱歉
猜你喜欢
  • 2021-01-02
  • 2017-03-08
  • 1970-01-01
  • 2017-03-27
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多