RnD
RnD

Reputation: 1069

C++ ifstream string

In a file I have pair of names on each line. Like this:

John Dave

Antoine Gerda

Sara Math

and so on...

What I want to do is to output that pair into one string. Like this:

string pairs[100];
ifstream inFile("duom.txt");
int n; //how many pairs

inFile >> n;
for(int i=1;i<=n;i++){
    inFile >> pairs[i];
}

This doesn't work because it reacts on the space.

getline(inFile,pairs[i]);

isn't acceptable as it skips a code after.

So my question is: would be there a possibility to read those 2 names into one string?

Upvotes: 0

Views: 608

Answers (1)

CapelliC
CapelliC

Reputation: 60004

the problem isn't getline, which is fine for your task, but the indexing. You should start from 0

for(int i=0;i < n;i++){
    getline(inFile, pairs[i]);
}

edit: as Kerrek SB noted, there could be a bug. after inFile >> n we should skip the newline: adding a dummy getline(inFile, pairs[0]); can get rid of it.

Upvotes: 3

Related Questions