Hi
Is it possible to read non-fixed amount of variables with one cin and push'em to a vector?
Thanks in advance
Printable View
Hi
Is it possible to read non-fixed amount of variables with one cin and push'em to a vector?
Thanks in advance
You will need to clarify. Obviously it is not possible to write a cin statement in the code reading a variable number of inputs in that statement, unless your program is generating, compiling, and invoking other code. (Unlikely.)
However, from a programming perspective there's no particular reason to impose this limitation. What is your actual goal?
As Lindley said, we need more details of your problem + what's your level of expertise in C++.
You could use std::copy with std::istream_iterator and std::back_inserter, something like:
This reads a variable number of integers from cin and pushes them in the vector vec.Code:vector<int> vec;
copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(vec));
if you don't know what indicates the end of the input, your program won't either now won't it?
I know what ends. The end of line.
There's n variables (the amount I'm given in runtime) anit's like that:
a b c d (n variables)
for n=3
Code:a b c
In that case, you want to read in an entire line, and then process that line.
There are several ways to do this.
- Process the line with regexes. This is usually efficient, but requires more knowledge of regexes.
- Feed the line into a string stream, and then read from that stream. There are two extra advantages with this approach:
---if the input is bad, it does not put your cin in a fail state.
---You are still processing streams, so you can reuse code, apply divide and conquer, or even recurse.
Here is an example using stringstream: My goal is to read an entire line, and then read each character 1 by 1 (NOTE: cin replaced by cin2 for slf containing example):
Code:#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
std::stringstream cin2(
"abc\n"
"def\n"
"gh"
);
int main()
{
std::string line;
while(std::getline(cin2, line))
{
std::cout << "Line: ";
std::istringstream issline(line);
std::istream_iterator<char> it_first(issline);
std::istream_iterator<char> it_last;
std::ostream_iterator<char> it_out(std::cout, "-");
std::copy(it_first, it_last, it_out);
std::cout << std::endl;
}
}
Code:Line: a-b-c-
Line: d-e-f-
Line: g-h-
And if I assume the input's always correct?
I'm making a prog to make my life easier
I'd be happy with an array of int
Yeah. But how then to read n variables in a row divided by spaces?
Well, the >> operator stops at whitespace, so simply doing
cin >> var[i];
in a loop would work. The only difficulty there is knowing when to stop, since a newline will be treated identically to any other whitespace with this method.
I would suggest first reading a single line into a std::string using getline(), and then parsing it as above using an istringstream.
thanks