首页 > 解决方案 > 在 C++ 中用 cin 读取同一行中的多个整数

问题描述

我从用户那里读取整数时遇到问题。我可以使用

int a, b, c;
cin >> a >> b >> c;

但我不知道用户会引入多少整数。我试过这个:

    int n;
    cin >> n; //Number of numbers
    int arrayNumbers[n];

    for(int i=0;i<n;i++){
    cin>>arrayNumbers[i]
    }

用户的输入将是: 1 2 3 我的意思是,在同一行。使用我以前的代码,它只得到第一个数字,而不是其余的。

我怎么能做到?

标签: c++inputcin

解决方案


首先使用 std::getline() 将整行读入字符串。然后从输入字符串创建一个字符串流。最后使用 istream_iterator 迭代各个令牌。请注意,此方法将在第一个不是整数的输入处失败。例如,如果使用输入:“1 2 ab 3”,那么您的向量将包含 {1,2}。

int main() {
        std::string str;
        //read whole line into str
        std::getline(std::cin, str);
        std::stringstream ss(str);
        //create a istream_iterator from the stringstream
        // Note the <int> because you want to read them
        //as integers. If you want them as strings use <std::string>
        auto start = std::istream_iterator<int>{ ss };
        //create an empty istream_iterator to denote the end
        auto end= std::istream_iterator<int>{};
        //create a vector from the range: start->end
        std::vector<int> input(start, end);
    
    }

推荐阅读