zoukankan      html  css  js  c++  java
  • 程序读文件的方式--按字符、按行、按单词

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

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

  • 相关阅读:
    铁轨
    POJ 2385 -- Apple Catching
    POJ 3258 -- River Hopscotch
    POJ 1469 -- COURSES (二分匹配)
    POJ 2349 -- Arctic Network
    最小生成树
    NOIP200703守望者的逃离
    NOIP200706字符串的展开
    POJ 1036 -- Gangsters
    POJ 1952 -- BUY LOW, BUY LOWER
  • 原文地址:https://www.cnblogs.com/kevinq/p/4492203.html
Copyright © 2011-2022 走看看