gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:35:39 26 4
gpt4 key购买 nike

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

首先我想我可以使用类似的东西

    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 个整数。

最佳答案

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

#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";

}

关于c++ - 如何从键盘读取 C++ 中可变数量的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53651663/

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