NadCo
NadCo

Reputation: 21

Text file containing empty spaces in c++!

I have a problem with reading a txt file of the following form:

    1 2 3 4 5 6 7 8 9 10
 1    f f   f   f f  
 2  f     f f   f f f
 3  f f   f   f f
 4  f f   f       f f 
 5      f   f f     f

where: (1,2,3,,,,,) are indeces, f's are data of type double.
I have tried to read the contents using matrix notation i.e. tab[i][j]; i've succeeded to do it when my file doesn't contain empty, but when it does have emty spaces as shown above, data is displayed randomly and i don't understand anything of it.

So, can anyone enlighten me please??

thanks in advance.

Upvotes: 1

Views: 316

Answers (2)

aldo
aldo

Reputation: 2987

If the data contains optional values each separated by (always) a single space character, I would try the string-reading approach given in the answer by @BenVoigt, then use a split function (there are many examples on StackOverflow and elsewhere), telling it NOT to remove empty values. This is the best way I can think of to deal with the multiple [Space] characters next to each other.

Thus if you have read a line of text like this:

[Space][Space]1.2[Space]3.4[Space]

You'll end up with an array (or vector or whatever) that contains:

"" (Empty string)
""
"1.2"
"3.4"
""

...which I think is what you're looking for.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283614

You'll want to use raw data reading functions, such as istream.get() or istream.read(), instead of the extraction operator (>>), because the extraction operator removes whitespace.

std::getline(istream&, string&) is also a good choice, because it preserves spaces.

Upvotes: 3

Related Questions