|
-
Nov 6th, 2002, 05:06 AM
#1
Thread Starter
Junior Member
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.
-
Nov 6th, 2002, 08:13 AM
#2
Monday Morning Lunatic
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|