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

#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()都将会向你展现出文件的本来面目。

相关文章:

  • 2022-12-23
  • 2021-08-16
  • 2021-11-25
  • 2021-08-01
  • 2021-07-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-08
  • 2022-02-21
  • 2021-05-30
  • 2021-08-01
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案