如何用空格和制表符区分分割文件行? [英] How to split a file lines with space and tab differentiation?
本文介绍了如何用空格和制表符区分分割文件行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下格式的文件
mon 01/01/1000(TAB)嗨你好(TAB)你好吗
mon 01/01/1000(TAB)hi hello(TAB)how r you
有什么方法可以单独使用 '\t'
作为分隔符(而不是空格)来阅读文本?
Is there any way to read the text in such a way to use '\t'
alone as delimiter (and not space)?
所以样本输出可以是,
星期一 01/01/1000
mon 01/01/1000
你好
你好吗
我不能使用 fscanf()
,因为它只读取到第一个空格.
I couldn't use fscanf()
, since it reads till the first space only.
推荐答案
仅使用标准库工具:
#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++中的字符串?
You can get some more ideas here: How do I tokenize a string in C++?
这篇关于如何用空格和制表符区分分割文件行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文