4

I tried looking up what I'm trying to do but I cant find specifically what I'm trying to do. I have a text file with multiple lines that look like this:

12345,12345,12.34,12345,12345

It's the same format on every line and I want to get each line and plug the numbers into certain variables. Something like this:

file >> int1 >> int2 >> double1 >> int3 >> int4;

But this is very hard for me to do because of the comma separating each number. I used to be able to do this when there was a 'space' but the comma is really throwing me off. Any ideas?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Arubix
  • 59
  • 2
  • 2
  • 8

3 Answers3

6
char ch;
file >> int1 >> ch >> int2 >> ch >> dbl >> ch >> int3 >> ch >> int4;
gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
4

You may want to try fscanf.

Something like this?

 fscanf(filepointer, "%d,%d,%f,%d,%d\n", &int1, &int2, &double1, &int3, &int4);
frsfnrrg
  • 136
  • 5
  • I'm an idiot. So wait, I'm new to this but since I'm using C++, then everything in C should work as well? – Arubix Apr 03 '13 at 21:09
  • 1
    @Arubix: Yes. It's a matter of debate as to whether you _should_ use any C library functions, though. At the very least, minimise your use of them. But for I/O often they're better. – Lightness Races in Orbit Apr 03 '13 at 21:23
  • @LightnessRacesinOrbit: Or worse. For example, scanf should *never* (and by never I mean almost never) be used with %s. – Robert Mason Apr 03 '13 at 21:32
0

The earlier suggestions work well. However, if you can use c++11 and need a more robust solution, I would suggest the c++11 regex library: http://en.cppreference.com/w/cpp/regex

Robert Mason
  • 3,949
  • 3
  • 31
  • 44