0

I have a csv file with the following information on each line:

John,Doe,17

The ifstream object name is inFile and I tried:

string firstName;
string lastName;
int age;
inFile >> firstName >> "," >> lastName >> "," >> age

However, clearly, i cannot do >> "," >>

How do I correctly get those values and use them?

Thank you.

D. Lin
  • 11
  • 1
  • 1
  • 5

2 Answers2

1

You can do it this way.

string firstName;
string lastName;
int age;
getline(inFile, firstName, ',');
getline(inFile, lastName, ',');
inFile >> age;

If you want to keep it consistent, you can use getline(inFile, ..., ',') for all data, then use std::stoi to convert age to integer. Or you can use getline(inFile, wholeline), and then use sscanf on the wholeline.

Hsi-Hung Shih
  • 233
  • 1
  • 7
  • string tempVariable; getline(inFile, tempVariable); string firstName; string lastName; char comma; float age; while(inFile >> firstName >> comma >> lastName >> comma >> age { Do you know why it never enters this loop? I use getline() to skip past the first line – D. Lin Feb 25 '16 at 03:31
  • `inFile >> firstName >> dummy >> lastName >> dummy >> age;` - this doesn't work - `>>` to a `std::string` consumes input until the next whitespace character or end-of-stream, so `"John,Doe,17"` ends up in `firstName`. – Tony Delroy Feb 25 '16 at 04:18
  • @D.Lin ah I didn't notice you don't have space before comma. – Hsi-Hung Shih Feb 25 '16 at 20:36
0

You'll want to use a stringstream and read each line into the stream using the comma as a delimiter. See: this question and its answer

Community
  • 1
  • 1
Brandon Haston
  • 434
  • 3
  • 5
  • The thing is my first line is the headers such as "first, last, age", how would I take that into consideration to not read that line then? – D. Lin Feb 25 '16 at 01:46
  • How about skipping first line? – Michael Nastenko Feb 25 '16 at 02:08
  • I'm hesitant to expand on my answer as I feel that it's more beneficial for one to experiment and work out the problem at hand, provided some guidance, as opposed to offering step-by-step instructions on what to do. With that said, concerning skipping a line, you don't have to do anything with a line when you read it (hint). – Brandon Haston Feb 25 '16 at 02:32
  • stringstream is not necessary because the infile is an istream and can be used the same way as stringstream mostly – Hsi-Hung Shih Feb 25 '16 at 20:45