std::ifstream using other separating character than space (' ')

Started by
0 comments, last by me22 18 years, 5 months ago
Is it possible to use another character than whitespace as a separating character? Like this:

// input.txt:
"A nice string"
"Another nice string" "string 3"


// blah.cpp:
void some_func()
{
   std::string temp;
   std::ifstream file("input.txt");

   while(file >> temp)
     std::cout << temp << std::endl;

}

So this would print: A nice string Another nice string string 3 Is this possible?
Advertisement
You cannot change the delimiter used by the built-in operator>>, to the best of my knowledge.

You might want std::getline, which gets up until a delimiter.

That or you could make your own function, perhaps something along the lines of the following:
std::istream &get_quoted(std::istream &source, std::string &str) {    char c = 0;    source >> c; // >> to skip whitespace    if ( c == '"' ) {        // if we read a ", store up to the next " in str        std::getline( source, str, '"' );    } else {        // if we read something that's not a ",        // put back whatever we read and read until whitespace        source.unget();        source >> str;    }    return source;}


Of course a robust version would handle \ as an escape sequence, allow ' as an alternate delimiter, ...

This topic is closed to new replies.

Advertisement