<分区>
我有一个格式如下的文件
mon 01/01/1000(TAB)hi hello(TAB)how r you
有没有办法以单独使用 '\t'
作为分隔符(而不是空格)的方式阅读文本?
所以示例输出可以是,
mon 01/01/1000
hi hello
how r you
我不能使用 fscanf()
,因为它只读到第一个空格。
标签 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/