zoukankan      html  css  js  c++  java
  • 【c++】输出文件的每个单词、行

    假设文件内容为

    1. hello1 hello2 hello3 hello4
    2. dsfjdosi
    3. skfskj  ksdfls

    输出每个单词

    代码

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <stdexcept>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string word;
        ifstream infile("text");
        if(!infile)
        {
            cout << "cannot open the file" << endl;
            return 0;
        }
        while(infile >> word)
            cout << "word:" << word << endl;
        infile.close();
    }

    结果

    分析

    定义文件流infile,并绑定文件“text”,之后判定,如果打开错误,则提示错误,结束程序。否则,继续执行程序:

    输入文件流infile把文件中的内容全部读入缓冲区(文件结尾符时停止往输入缓冲区内存),通过重定向符>>传到word(间隔福为Tab, Space, Enter)

    输出每一行

    代码

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <stdexcept>
    #include <string>
    
    int main()
    {
        ifstream infile;
        string line;
        infile.open("text");
        if(!infile)
            cout << "error: cannot open file" << endl;
        while(getline(infile, line))
        {
            cout << "line:" << line << endl;
        }
        infile.close();
    }

    结果

    分析

    函数原型:istream& getline ( istream &is , string &str , char delim );

    is为输入, str为存储读入内容的字符串(不存储分割符), delim为终结符(不写默认为' ')

    返回值与参数is一样

    同时输出每行和该行的每一个单词

    代码

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    #include <stdexcept>
    using namespace std;
    
    int main()
    {
        ifstream infile;
        string line, word;
        infile.open("text");
        if(!infile)
            cout << "error: cannot open file" << endl;
        while(getline(infile, line))
        {
            cout << "line:" << line << endl;
            istringstream instream(line);
            while(instream >> word)
                cout << "word:" << word << endl;
            cout << endl;
        }
        infile.close();
    }

    结果

    分析

    <<是类istream 定义的,istringstream, ifstream 是其子类,都可以用

    >>是类ostream 定义的,ostringstream, ofstream 是其子类,都可以用

    用读出的每行初始化字符串流,在输出赋给单词(依旧分隔符隔开,但没有分隔符的事儿)

  • 相关阅读:
    Flex Box 简单弹性布局
    CSS 0.5px 细线边框的原理和实现方式
    前端模块化方案全解(CommonJS/AMD/CMD/ES6)
    用信鸽来讲解HTTPS的知识
    __name__ == "__main__"的作用是什么?
    如何自学计算机科学与技术(Teach Yourself Computer Science)
    中文技术文档的写作规范
    'adb remount'的作用是什么?在什么情况下有用?
    使用python遍历文件夹取出特定的字符串
    Python&Appium实现安卓手机图形解锁
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3466141.html
Copyright © 2011-2022 走看看