views:

819

answers:

2

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.

A: 

Your code looks fine. Are you sure about the contents of your text file?

R Samuel Klatchko
A: 

Assuming that there is a blank line between two sets of clients, std::getline reads in characters until the delimiter character is found. This is by default \n, so an empty line,

line1

line3

or line1\n\nline3 will have you reading in an empty string for that empty line if you called std::getline twice.

tJener