【问题标题】:How to split a file lines with space and tab differentiation? [duplicate]如何用空格和制表符区分文件行? [复制]
【发布时间】:2012-05-23 22:19:47
【问题描述】:

我有一个格式如下的文件

1000 年 1 月 1 日星期一(TAB)你好(TAB)你好吗

有没有什么方法可以单独使用'\t' 作为分隔符(而不是空格)来阅读文本?

所以样本输出可以,

1000 年 1 月 1 日星期一

你好

你好吗

我不能使用fscanf(),因为它只读取到第一个空格。

【问题讨论】:

    标签: c++ string split tabs whitespace


    【解决方案1】:

    仅使用标准库设施:

    #include <sstream>
    #include <fstream>
    #include <string>
    #include <vector>
    
    std::ifstream file("file.txt");
    
    std::string line;
    
    std::vector<std::string> tokens;
    
    while(std::getline(file, line)) {     // '\n' is the default delimiter
    
        std::istringstream iss(line);
        std::string token;
        while(std::getline(iss, token, '\t'))   // but we can specify a different one
            tokens.push_back(token);
    }
    

    您可以在这里获得更多想法:How do I tokenize a string in C++?

    【讨论】:

      【解决方案2】:

      来自提升:

      #include <boost/algorithm/string.hpp>
      std::vector<std::string> strs;
      boost::split(strs, "string to split", boost::is_any_of("\t"));
      

      您可以在其中指定任何分隔符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2021-09-28
        相关资源
        最近更新 更多