How do I include spaces in ifstream?

This is a discussion on How do I include spaces in ifstream? within the C++ Programming forums, part of the General Programming Boards category; I am trying to make a program that writes information out to a text file on exit and reads it ...

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    49

    How do I include spaces in ifstream?

    I am trying to make a program that writes information out to a text file on exit and reads it back into the program when it is started again. I am using fstream to do this. I'm having an issue with spaces . I can write a string out to the text using ofstream.

    Code:
    string name = "Bob Patterson";
    ofstream output( "data.txt", ios::out );
    output << name << endl; //writes the name "Bob Patterson to the file data.txt
    
    string inputName;
    ifstream input( "data.txt", ios::in );
    input >> inputName;
    cout << inputName; //this only outputs the first name "Bob" I want it to say "Bob Patterson";
    However when I read it back into the program on startup it only reads until the space and completely misses the next word. How do I fix this?
    Last edited by rakan; 10-01-2006 at 06:34 PM.

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    Try using getline() as like this:

    Code:
    std::getline(input, inputName, '\n');

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    49
    Thanks. If I do this..

    Code:
    string inputName;
    ifstream input( "data.txt", ios::in );
    getline(input, inputName, '\n');
    input >> inputName;
    cout << inputName;
    It seems to work. What does that getline command do?

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    903
    It does what its name says. It gets a line. It uses the last parameter as a delimiter (the character determining what is a line and what is not). If I recall correctly, cin discards spaces.

  5. #5
    pwns nooblars
    Join Date
    Oct 2005
    Location
    Portland, Or
    Posts
    1,094
    Using the << is going to grab everything up to the first space I do believe... effectivly it is the same as using getline(iStream, var, ' ');

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Socket programming
    By kahad in forum C Programming
    Replies: 3
    Last Post: 12-14-2006, 03:37 PM
  3. limits.h problem!!
    By guitarist809 in forum C++ Programming
    Replies: 21
    Last Post: 04-13-2006, 10:28 PM
  4. Multiple include problem
    By VirtualAce in forum Game Programming
    Replies: 13
    Last Post: 02-04-2006, 05:09 PM
  5. How to include spaces in c++
    By holoduke in forum C++ Programming
    Replies: 8
    Last Post: 12-05-2002, 12:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21