c++ - 如何用空格和制表符区分文件行?

标签 c++ string split tabs whitespace

<分区>

我有一个格式如下的文件

mon 01/01/1000(TAB)hi hello(TAB)how r you

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

所以示例输出可以是,

mon 01/01/1000

hi hello

how r you

我不能使用 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);
}

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

关于c++ - 如何用空格和制表符区分文件行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10617094/

相关文章:

c++ - 将 `nullptr` 分配给 `bool` 类型。哪个编译器是正确的?

ruby-on-rails - 在 Rails 2.0/ruby 1.8.6 中,如何在字符串数组中找到非 ascii 字符串?

python - 在 Python 中解析和清理商店营业时间的文本 block

python/numpy 一次合并 4 行子数组

java - 用分隔符分割字符串

c++ - 为什么 stable_sort 会影响我的哈希表值?

c++ - 模板类的运算符<<()

Android Crashlytics - 无法上传符号

Python设置字符串的差异

javascript - 将表中的值拆分为不同的文本输入?