How to read numbers (separated by spaces) into an array?
Input (getline): 100 231 144 123 551
tab[0] = 100;
tab[1] = 231;
...
How I can do this ?
How to read numbers (separated by spaces) into an array?
Input (getline): 100 231 144 123 551
tab[0] = 100;
tab[1] = 231;
...
How I can do this ?
std::cin >> i
breaks on whitespace by default. If you want to handle things on a per-line basis, you could use a std::istringstream
.
If the line is mutable, you can just replace spaces with zeros, counting elements on the way if you want a single correct allocation, and use atoi
on a second pass..
The stupid way is to read the string byte-by-byte and do the translation yourself.
Or you can use sscanf
:
char input[] = "100 231 144 123 551"
sscanf(input, "%d%d%d%d%d", tab[0], tab[1], tab[2], tab[3], tab[4]);
But I guess you are actually using getline
of an istream
object - if this is the case, you may just use the operator >>
instead:
if it is the standard input stream cin
:
cin>>tab[0]>>tab[1]>>...
or, if it is a file stream fin
:
fin>>tab[0]>>tab[1]>>...
In the above, I always suppose that you know the number of numbers in the array. If you don't, then you should have something as symbol of termination - then basically you just read numbers until encounter the symbol. It will then depend on what exactly is the symbol.