c++ - 读取 2 个整数并在 while 循环中打印它们的程序给出 range_error

标签 c++

来自 Programming: principals and practices Chapter 4 Drill 1:

编写一个由 while 循环组成的程序(每次围绕 loop) 读入两个 int 并打印它们。退出程序时 输入终止 'I'

到目前为止,代码一直在崩溃。当我调试时,它看起来像是在第 20 行崩溃并出现 range_error。我查了一下,它说这是因为它试图访问不存在的东西。

| 代码还说 没有从 'const char *' 到 'int' 的转换 我怎么能把那个符号作为 int 所以它可以终止?我认为像 (char)x 这样的做法是正确的!

如果您有解决方案,请保持简单,因为我只在第 4 章学习,而且我刚刚学习了循环和 vector 。

#include "std_lib_facilities.h"

using namespace std;

int main()
{
    int x = 0;
    vector<int> tuggo;

    cout << "Enter two ints:" << endl;
    cout << "Enter a | to terminate program instead.";

    while(cin>>x)
    {
        if ((char)x == "|")
            break;
        tuggo.push_back(x);
            if (tuggo.size() == 1)
            {
                cout << tuggo[0] << tuggo[1] << endl;
                keep_window_open();
                break;
            }
            else if (tuggo.size() < 1)
                cout << "Too much data, this crappy program only can handle two integers." << endl;
    }
}

最佳答案

当您的 vector 大小为 1 时,您尝试访问 2 个元素 - 那是您的范围异常。

关于c++ - 读取 2 个整数并在 while 循环中打印它们的程序给出 range_error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985511/

相关文章:

c++ - 获得两倍宽的字体

c++ - 如何在Linux终端应用程序中检测XOFF和XON

c++ - cocos2dx 检测与多边形 Sprite 的交集

c++ - 在 C++ 中将可变大小的 TensorFlow 张量转换为 std::vector

c++ - OpenGL:缩放自适应网格线

c++ - 如何在头文件中的结构中为数组初始化和分配内存?

c++ - Qwt 和 QwtSeriesData

c++ - 从可执行文件中提取静态链接库

c++ - 为没有默认构造函数的类型初始化静态大小的数组

c++ - 将分配的 C++ 数组传递给 Fortran 子例程