Results 1 to 2 of 2

Thread: Outputting contents of text file to screen.

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Sep 2002
    Posts
    19

    Outputting contents of text file to screen.

    Hi,

    Just a quick C++ problem. Trying to open a text file and output the contents to the screen. Seemingly an easy task, but I can't find a good example on the net anywhere

    My code is:

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    
    int main()
    {
    
     ifstream ins;
     string word;
     char c;
     
     // Open up the text file and read the data.
     // Print and error if we can't open it.
     ins.open("data.txt");
     
     if(ins.fail())
     {
      cout << "Cannot read file." << endl;
      return 0;
     }
     
     while (ins >> word)
     {
      ins.get(c);
      cout << c;
     } 
    
    }
    It compiles and executes, however it doesn't print anything to the screen. I know I have done something really stupid, however I don't have a clue what it is.

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Code:
    while (ins >> word)
     {
      ins.get(c);
      cout << c;
     }
    What you're doing here is retrieving a word from the file, then getting another character and printing that. Try cout << ' ' << word to print the word out.

    I would suggest using getline though, otherwise you risk losing information from the file:
    Code:
    while(!ins.eof()) {
        string line;
        getline(ins, line);
        cout << line << endl;
    }
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width