来自 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/