Text File I/O

O

ophelia

hello, i am a beginner at C++ and i'm currently trying to write a small
application that reads a text file and display it out on screen. My
problem is that instead of reading the text file line by line, im
getting it as character by character, seperated by spaces! :( for
instance if the text file has the following data :

hello people!
my name is ophelia.

the output on screen that i'm getting is :

h e l l o p e o p l e !
m y n a m e i s o p h e l i a .


my code is as follows :

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}

else cout << "Unable to open file";

return 0;

please..can anyone help me? is there something missing? thank you all
in advance. *muak*
 
J

Jonathan Mcdougall

ophelia said:
hello, i am a beginner at C++ and i'm currently trying to write a small
application that reads a text file and display it out on screen. My
problem is that instead of reading the text file line by line, im
getting it as character by character, seperated by spaces! :( for
instance if the text file has the following data :

hello people!
my name is ophelia.

the output on screen that i'm getting is :

h e l l o p e o p l e !
m y n a m e i s o p h e l i a .

It's not the code, it may be the file. Make sure it is encoded in
ASCII, not Unicode.

As for the code..
my code is as follows :

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )

Careful: EOF is detected *after* reading.
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5
{
getline (myfile,line);
cout << line << endl;
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.7

}
myfile.close();

Redundant, the stream's destructor closes the file.
}

else cout << "Unable to open file";

When you use bracket, use them everywhere.

else
{
std::cout << "Unable to open file";
}
return 0;
Redundant.

*muak*

... what?


Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top