8

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.

iammilind
  • 65,167
  • 30
  • 162
  • 315
John
  • 1,825
  • 12
  • 32
  • 43

2 Answers2

13

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++?

Andrejs Cainikovs
  • 25,695
  • 2
  • 70
  • 92
jrok
  • 52,730
  • 9
  • 104
  • 139
5

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.

WeaselFox
  • 7,100
  • 7
  • 42
  • 73