How do I read ints separated by commas in a file?

I'm trying to read something like this:

1. Oliver, 42, 405023, 12

I know about the getline(readFile,string,',') thing but how do I apply it to ints or doubles? I don't want to store the numbers in a string

Also...

1. Do I just put a placeholder string to take the "1." out of the picture?

2. Would the commas be read into the int and create a mess if I just do it normally? (ex: using readFile>>int; on "42,")
Last edited on
There's probably an easier way but:
1
2
3
#include <string>
#include <fstream>
#include <sstream> 


1
2
3
4
5
int i;
std::string line;
std::getline(readFile, line, ',');
std::stringstream iss(line);
str >> i;
Much appreciated, but this particular program is for a class though, I need to make sure I know what I am doing and well we haven't covered anything related to the <sstream> header yet

Is there another way to work around this problem with simple functions?

I like the suggestion from Stewbond.

If you have an input file which consists of multiple lines like this:
1. Oliver, 42, 405023, 12

then the most obvious approach is to read an entire line in one go into a string. Then use a stringstream to parse the line into individual words. And having already used stringstream once, it seems a small step to use it again to convert the string to int.

These two lines convert a string into an int:
1
2
    std::stringstream iss(line);
    str >> i;


An alternative way is to do this:
 
    int i = atoi(line.c_str());

using the <cstdlib> header.


Last edited on
Topic archived. No new replies allowed.