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

20,236

Solution 1

Using only standard library facilities:

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

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

Solution 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.

Share:
20,236
John
Author by

John

Live Every Moment

Updated on July 09, 2022

Comments

  • John
    John almost 2 years

    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.