gpt4 book ai didi

c++ - 在 C++ 中用 cin 读取同一行中的多个整数

转载 作者:行者123 更新时间:2023-12-03 06:53:44 26 4
gpt4 key购买 nike

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

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我的意思是,在同一行。使用我以前的代码,它只得到第一个数字,而不是其余的。

我该怎么做?

最佳答案

首先使用 std::getline() 将整行读入一个字符串。然后从输入字符串创建一个字符串流。最后使用 istream_iterator 迭代各个标记。请注意,此方法将在第一个非整数输入时失败。例如,如果使用输入:“1 2 ab 3”,那么您的 vector 将包含 {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);

}

关于c++ - 在 C++ 中用 cin 读取同一行中的多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62865398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com