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;
>> 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;
>> }


No comments:

Post a Comment