You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中cin跳过sums输入,未获用户输入直接赋值1的问题求助

问题原因

第一个while (cin >> userinput)循环结束时,cin已经触发了错误状态位(failbit 或 eofbit)——这是因为你输入完数字后,会输入非整数内容(比如字母)或者按Ctrl+Z/Ctrl+D触发EOF来终止循环,此时cin进入错误状态,后续所有输入操作都会直接跳过,导致cin >> sums根本没读取你的输入,你看到的sums值为1只是栈内存的随机值。

你之前只调用cin.clear()没用,因为这个函数仅清除错误状态位,但输入缓冲区里残留的无效字符(比如结束循环时的非数字内容、换行符)还在,后续cin会直接跳过这些内容,依然无法读取有效输入。

修复方案

在第一个循环结束后,先清除cin的错误状态,再清空输入缓冲区的所有残留字符,同时可以加个越界判断避免程序崩溃,修改后的代码如下:

#include <iostream>
#include <vector>
#include <limits> // 需包含此头文件使用numeric_limits

using namespace std;

int main() {
    int userinput;
    int sums;
    int sum = 0;
    vector<int> nums;
    
    cout << "Enter as many numbers as you'd like." << endl;
    while (cin >> userinput) {
        nums.push_back(userinput);
    }
    
    // 修复输入状态
    cin.clear(); // 清除cin的错误标记
    // 清空输入缓冲区中直到换行的所有残留字符
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    
    cout << "Enter the numbers you want to add: ";
    cin >> sums;
    
    // 防止sums超过vector元素数量,避免越界访问
    if (sums > nums.size()) {
        sums = nums.size();
        cout << "Warning: Input number exceeds the count of entered numbers, will sum all numbers instead." << endl;
    }
    
    for (int i = 0; i < sums; ++i) {
        sum += nums[i];
    }
    
    cout << "The sum of the first " << sums << " numbers is: " << sum << "." << endl;
    
    return 0;
}
补充说明
  • numeric_limits<streamsize>::max()表示输入缓冲区的最大容量,确保能一次性清空所有残留字符。
  • 新增的越界判断可以避免用户输入的sums值大于vector元素数量时,程序因访问非法内存崩溃。

内容的提问来源于stack exchange,提问作者jnasdandas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 01:17:24