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 是其子类,都可以用

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

  • 相关阅读:
    同样功能的SQL语句,写成参数和写成常量怎么效率会有那么大的差别
    遭遇钓鱼网站
    SQL Server 2005与Oracle同步注意NUMBER类型转换
    Oracle数据类型(转)
    如何使用枚举的组合值
    社保,交得越多亏得越多(转)
    使用OPENXML函数将XML文档转换为行结果集
    发布一个性能测试工具的破解补丁
    如何将SQLServer2005中的数据同步到Oracle中
    Repository模式
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3466141.html
Copyright © 2011-2022 走看看