9

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
  • 68,093
  • 33
  • 169
  • 336
John
  • 2,035
  • 13
  • 35
  • 44

2 Answers2

14

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
  • 27,428
  • 2
  • 75
  • 95
jrok
  • 54,456
  • 9
  • 109
  • 141
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,220
  • 8
  • 44
  • 75