如何拆分具有空格和制表符区分的文件行

How to split a file lines with space and tab differentiation?

本文关键字:制表符区 文件 空格 何拆分 拆分      更新时间:2023-10-16

我有一个以下格式的文件

星期一 01/

01/1000(TAB)嗨,你好(TAB)你好吗

有没有办法以单独使用't'作为分隔符(而不是空格)的方式阅读文本?

所以样本输出可以是,

星期一 01/01/1000

嗨,你好

你好吗

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

仅使用标准库工具:

#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);
}

您可以在此处获得更多想法:如何在 C++ 中标记字符串?

来自 boost :

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

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