GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Saturday, December 18, 2010

C++ - Reading From Text File

To read from a text file, you need to type like below plus include <fstream> header file:

>> string text;
>> ifstream data;
>> data.open("D://data.txt");
>> getline(data,text);     // just for one line
>> data.close();

if you use:
>> data >> text;
so, you just get one word, not more.

if you use:
>> getline(data,text);    // same as getline(cin,text)
you will get one line, note more.

if you want to get words or lines, you need
>> getline(data,text,'#');    // getline(cin,text,'#')
where "#" is a char at the file as a sign for end.

To read full of file, you need use eof():
>> while(!data.eof()){
>>     getline(data,text);
>>     cout << text << endl;
>> }

 
Share/Bookmark

No comments:

Post a Comment