2

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 ?

Mongow
  • 59
  • 1
  • 10
  • You most like want to split the string and then do the assigment: http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – frlan Feb 01 '14 at 23:51

2 Answers2

3

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..

spraff
  • 32,570
  • 22
  • 121
  • 229
1

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.

WhatsUp
  • 1,618
  • 11
  • 21
  • Stupid solution. I don't know how much will the numbers. – Mongow Feb 02 '14 at 12:18
  • Way to treat the guy that spends his time giving you the most detailed answer. By the way you said "array", which has static size. So you absolutely *do* know how many numbers to scan. – tenfour Feb 02 '14 at 14:00