程序读文件的方式--按字符、按行、按单词

程序读文件的方式--一个字符一个字符进行读取

#include <iostream>
#include <fstream> 
using namespace std;
int main()
{
    char ch;
    fstream fp("a.txt");
    while(!fp.eof())
    {
        if(fp.get(ch))
            cout<<ch;
    }
    fp.close();
    return 0;
}
程序读文件的方式--逐行读取
#include <iostream>
#include <fstream> 
using namespace std;
int main()
{
    char line[100];
    fstream fp("a.txt");
    while(!fp.eof())
    {
        fp.getline(line, 100);
        cout<<line<<endl;
    }
    fp.close();
    return 0;
}

程序读文件的方式--一个单词一个单词进行读取

#include <iostream>
#include <fstream> 
using namespace std;
int main()
{
    char str[20];    //string str;
    fstream fp("a.txt");
    while(!fp.eof())
    {
        fp>>str;
        cout<<str;
    }
    fp.close();
    return 0;
}

建议使用逐行读取的方式,或者是逐字符读取的方式。逐词读取的方式并非一个好的方案,因为它不会读出新起一行这样的信息,
所以如果你的文件中新起一行时,它将不会将那些内容新起一行进行显示,而是加在已经打印的文本后面。而使用 getline()或者
get()都将会向你展现出文件的本来面目。

posted @ 2015-05-10 14:19  codeplayplus  阅读(247)  评论(0编辑  收藏  举报