Reputation: 261
So I am writing a program that deals with reading in and writing out to a file. I use the getline() function because some of the lines in the text file may contain multiple elements. I've never had a problem with getline until now. Here's what I got.
The text file looks like this:
John Smith // Client name
1234 Hollow Lane, Chicago, IL // Address
123-45-6789 // SSN
Walmart // Employer
58000 // Income
2 // Number of accounts the client has
1111 // Account Number
2222 // Account Number
And the code like this:
ifstream inFile("ClientInfo.txt");
if(inFile.fail())
{
cout << "Problem opening file.";
}
else
{
string name, address, ssn, employer;
double income;
int numOfAccount;
getline(inFile, name);
getline(inFile, address);
// I'll stop here because I know this is where it fails.
When I debugged this code, I found that name == "John", instead of name == "John Smith", and Address == "Smith" and so on. Am I doing something wrong. Any help would be much appreciated.
Upvotes: 1
Views: 9059
Reputation: 534
The code you show should work on that file. So something must be different than you think. The most likely culprits are:
inFile >> name
where you think it uses getline(inFile,name)
Perhaps you changed something and forgot to save or recompile or you are reading a a different file than you think.
By the way, from your variable declarations it looks like you may be planning to mix getline()
calls with extraction operator calls like inFile >> income
. Mixing these requires care because the extraction operator leaves behind trailing whitespace that getline()
might then read. There's more information near the bottom of this.
Upvotes: 2