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

 ̄綄美尐妖づ 提交于 2019-12-10 03:05:45

问题


I have a file in below format

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

Is there any way to read the text in such a way to use '\t' alone as delimiter (and not space)?

So sample output can be,

mon 01/01/1000

hi hello

how r you

I couldn't use fscanf(), since it reads till the first space only.


回答1:


Using only standard library facilities:

#include <sstream>
#include <fstream>
#include <string>
#include <vector>

std::ifstream file("file.txt");

std::string line;
std::string partial;

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

You can get some more ideas here: How do I tokenize a string in C++?




回答2:


from boost :

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

you can specify any delimiter in there.



来源:https://stackoverflow.com/questions/10617094/how-to-split-a-file-lines-with-space-and-tab-differentiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!