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?
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):
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
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
If you want an easy life, then use a vector, not an array.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
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.
Bookmarks