如何从键盘读取 C++ 中可变数量的整数?

How to read from keyboard a variable number of integers in C++?

我需要从键盘读取可变数量的整数,以便我可以使用它们中的每一个。

首先我想我可以使用像

这样的东西
    int myinteger;
    for (int i=0; i<MAX_NUMBER_OF_INTEGERS; i++){
    cin >> myinteger;
    //What I want to do with that Integer
    }

但后来我意识到,如果 MAX_NUMBERS_OF_INTEGERS = 10 我必须写 10 个整数。但我想要的是我可以传递“1 2 3”“1 2 3 4”(例如)而不必写 10 个整数。

std::vector<int> read_ints;
int _temp;
for(;;)
{        
    cin >>_temp;
    if(!cin.good()) {
        break;
    }
    else {
        read_ints.push_back(_temp);
    }
}

我没有测试过这个解决方案,但它应该从 cin 中读取任意数量的整数,直到您输入整数以外的内容。如果不需要保存结果,也可以跳过矢量部分的保存。如果您想保存任意数量的整数,这只是相关的。

编辑:澄清后您的解决方案可能如下所示:

 int MAX_CHARS = 10;
 int my_int;
 cin >> setw(MAX_CHARS) >> my_int;

setw 限制了输入字符的数量,但你必须包括 iomanip header

如果要访问每个数字,请使用此函数将 int 转换为 int 向量:

vector <int> integerToArray(int x)
{
    vector <int> resultArray;
    while (true)
    {
        resultArray.insert(resultArray.begin(), x%10);
        x /= 10;
        if(x == 0)
            return resultArray;
    }
 }

然后您可以使用索引访问每个数字,例如第一个数字

 vectory<int> resultArray = integerToArray(my_int);
 int digit = resultArray[0];

Source

从一行中读取所有数字并将其限制为最大整数数量的一种方法是使用 std::getline() 将该行转换为字符串,然后在循环中使用 istringstream。

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    std::string line; 
    std::getline (std::cin,line); 
    std::istringstream iss(line);

    int myInt;

    for(int i=0;(iss >> myInt) && (i < MAX_NUMBER_OF_INTEGERS);++i ) {
        std::cout << myInt << ' ';
    }

    return 0;
}

注意:我没有在代码中定义MAX_NUMBER_OF_INTEGERS。我可以在使用前用 const int MAX_NUMBERS_OF_INTEGERS = 10; 定义它,或者可能是预处理器定义甚至是命令行参数。我把这个留给用户。

这个问题自从被问到并给出了很好的答案后,似乎发生了一些变化。这只是为了回答新问题。

#include <iostream>
#include <sstream>
#include <vector>

const int MAX_NUMBERS_OF_INTEGERS = 10;

int main() {
    std::string line;
    std::cout << "Enter at most " << MAX_NUMBERS_OF_INTEGERS << " ints, separated by spaces: ";
    std::getline(std::cin, line);

    // create a string stream of the line you entered
    std::stringstream ss(line);

    // create a container for storing the ints
    std::vector<int> myInts;

    // a temporary to extract ints from the string stream
    int myInteger;

    // extract at most MAX_NUMBERS_OF_INTEGERS ints from the string stream
    // and store them in the container
    while(myInts.size()<MAX_NUMBERS_OF_INTEGERS && ss>>myInteger) myInts.push_back(myInteger);

    std::cout << "Extracted " << myInts.size() << " integer(s)\n";

    // loop through the container and print all extracted ints.
    for(int i : myInts) {
        std::cout << i << "\n";
    }
    // ... or access a certain int by index
    if(myInts.size() > 2)
        std::cout << "The third int was: " << myInts[2] << "\n";

}