I want to take several integers as input until newline ('\n', not EOF) occurs then put them into an array
or a vector
. How can I do that using keywords that are exclusive to C++?
Here is something that uses more C++ functions and data structures:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::vector<int> database;
std::string text_line;
std::getline(std::cin, text_line);
std::istringstream input_stream(text_line);
int value;
while (input_stream >> value)
{
database.push_back(value);
}
// Edit 1: printing the vector
for (auto&& v:database)
{
std::cout << v << " ";
}
std::cout << "\n";
return EXIT_SUCCESS;
}
In the above program, a line of text (i.e. text until newline), is read into the string variable.
The string is then treated as an input stream and all the numbers in the string are placed into the vector.
The string helps to limit to only numbers input from the line of text.