C++ 从控制台读取整数数组

c++ read integer array from console

本文关键字:整数 数组 读取 控制台 C++      更新时间:2023-10-16

所以我在从控制台读取一些数字时一直试图摆脱无限循环。这是读取部分代码:

vector<int> all;
string input;
while (getline(cin, input)) {
    int number;
    stringstream ss(input);
    while (ss >> number) {
        all.push_back(number);
    }
}

我也试过这个:

vector<int> all;
while (cin >> number) {
    all.push_back(number);
}

解决此问题的一种快速方法是在从控制台输入空行时中断外部循环:

while (getline(cin, input))
{
   if (input == "")
       break;
    ...
}

注意:某些实现在 getline 中的行尾返回一个回车符,它只条带化新行(换行符(http://www.cplusplus.com/reference/string/string/getline/

如前所述,这是一种非常简单快捷的退出无限循环的方法,从用户的角度来看,他/她可以输入由空格、制表符、Enter 或任何组合分隔的数字,您的向量将被填充,直到用户输入空行。

您的代码将如下所示:

#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    vector<int> all;
    string input;
    while (getline(cin, input)) {
        if (input == "")
            break;
        int number;
        stringstream ss(input);
        while (ss >> number) {
            all.push_back(number);
        }
    }
    // Here the vector "all" has any numbers entered by user
    return 0;
}