c++ - 无法在以下代码中输入n(cin >> n)

标签 c++ error-handling

/**

编写一个程序,该程序读取一系列数字并将其存储在 vector 中。用户输入了他或她希望输入的所有数字后,询问用户要累加多少个数字。对于答案N,请打印 vector 的前N个元素的总和。例如:“请输入一些数字(在提示符下按'I'停止):“12 23 13 24 15”请输入您希望求和的数字,从第一个数字开始:“3”前三个数字:12、23和13是48。”处理所有输入。例如,如果用户要求的总数大于 vector 中的总数,请确保给出错误消息。

**/

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    try
    {

    vector<int> numbers;
    int num;

    cout<<"Now enter the numbers";

    while(cin>>num)
    numbers.push_back(num);

    int n,sum=0;
    cout << "Enter the nth number to find sum of elements till n : ";
    cin>>n;

    if(n >numbers.size())
    throw 66;

    for(int i=0;i<n;i++)
    sum+=numbers[i];

    cout << "sum is "<<sum;

    return 0;
}

catch(int k)
{
        cerr<<"Error "<<k;
        return -1;
}
}

因此,当我输入EOF,CTRL + D时,程序终止。我不确定哪里出了问题。我什至尝试使用gdb进行调试(在在线教程的帮助下)。它不仅解决了。有人可以告诉我代码有什么问题吗?

最佳答案

您没有检查您是否实际阅读了任何东西。

Consider this little test program:

#include <iostream>

int main()
{
    std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";

    int n = -42;
    std::cin >> n;
    std::cout << n << "\n";
    std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";

    n = -42;
    std::cin >> n;
    std::cout << n << "\n";
    std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";
}

当输出为空的标准输入(等效于立即用ctrl + d声明其结束)时,输出为:

std::cin is ready
-42
std::cin is done
-42
std::cin is done



如您所见,n永远不会更改,因为永远不会有新值将其更改为!另外,您可以轻松地发现std::cin的状态反射(reflect)了先前的读取是否结束了。

由于仅检查整数值而不确保它们具有默认值(如果没有通过读取输入来设置,请检查n发生了什么),这很容易导致程序表现出意外的行为。

注意:测试程序is different when fed input that simply is not a number的行为。

关于c++ - 无法在以下代码中输入n(cin >> n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29506319/

相关文章:

c++ - OpenGL着色器输入

c++ - 如何决定何时实现 C++ 模板?

error-handling - Antlr4识别错误后,如何要求应用程序自动修复它?

python - 调用函数时,try/except语句在哪里?

javascript - 在$ .ajax()调用之一中转义$ (“html”).ajaxError()

node.js - 在Node js中使用fs读取json文件时出错

c++ - 如何从头开始在 VS 2019 中设置 Google Test?

c++ - 从客户端获取输入到服务器

c++ - 序列元组

language-agnostic - 错误说明指南