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.

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
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.
@D.Lin ah I didn't notice you don't have space before comma.
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

4 Comments

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?
How about skipping first line?
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).
stringstream is not necessary because the infile is an istream and can be used the same way as stringstream mostly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.