Thread: strings and file i/o

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    1

    Question strings and file i/o

    Hi all,

    I have what is hopefully a simple question:

    I'm reading input from a file with the usual statement:

    ifstream infile("input.txt");

    The file contains simple statements of 2 or 3 words, separated by spaces, one statement per line.

    How can I get the input from the file in string format? I have tried every C++ trick I can think of (and even a few that I don't really understand!) but still can't get it to work. I need strings so that I can compare substrings to pre-defined variables

    - infile.getline(...) doesn't work, it needs an array of char's as it's first parameter, not a string
    - infile >> string_name doesn't work because the string is cut off at the first space

    Is it possible?

    Thanks,
    batgirl

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Global getline() will take a string as an argument -

    ifstream fin("yourFile");
    string str;
    getline(fin,str,'\n');

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4

    Lightbulb strings and file I/O

    HEY BATGIRL,
    TRY THIS.


    char arr[30]//depends upon the number os characters in ur file.
    ifstream infile("input.txt",ios::in);
    infile.getline(arr,20);
    cout<<arr;

    there u have it..ur problem solved.!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  2. I/O with strings
    By kristentx in forum C++ Programming
    Replies: 1
    Last Post: 09-13-2007, 02:18 AM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. File I/O and Strings
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 05-25-2002, 10:02 PM