1

Is there a default delimiter for stringstream? From my research, I understood that I can use it to split a string using space and comma as delimiters. But can I use other delimiters for stringstream? Here is a C++ code snippet :

vector<int> parseInts(string str) {
    // Complete this function
    stringstream ss(str);
    vector<int> res;
    char ch;
    int x;
    while(ss){
        ss >> x >> ch;
        res.push_back(x);
    }
    return res;
}

This code works without me mentioning any specific delimiter. How does that happen?

Sam7834
  • 23
  • 1
  • 4
  • 1
    Did you check with a `C++` reference manual? – Galik Jun 04 '20 at 20:18
  • Does this answer your question? [How to use stringstream to separate comma separated strings](https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings) – anastaciu Jun 04 '20 at 20:20
  • `while (ss) { ss >> x >> ch; ... }` should be `while (ss >> x >> ch) { ... }` instead, but do note that it will fail to enter the loop body on the last value in the stream if there is no trailing delimiter that can be read into `ch`. You can avoid that by using something like `while (ss >> x) { ... if (!(ss >> ch)) break; }` or `while (ss >> x) { ... if (ss.peek() == stringstream::traits_type::eof()) break; ss.ignore(); }` instead. – Remy Lebeau Jun 04 '20 at 22:52
  • How to use stringstream to separate comma separated strings – I could not clear my doubts with this. But thanks for the share. – Sam7834 Jun 05 '20 at 16:28

1 Answers1

1

There is no "delimiter" for streams at all. operator>>, on the other hand, implements its reading by delimiting on whitespace characters. For other delimiter characters, you can use std::getline() instead, eg:

vector<int> parseInts(string str) {
    // Complete this function
    istringstream iss(str);
    vector<int> res;
    int x;
    string temp;
    char delim = '-'; // whatever you want
    while (getline(iss, temp, delim)) {
        if (istringstream(temp) >> x) { // or std::stoi(), std::strtol(), etc
            res.push_back(x);
        }
    }
    return res;
}

This code works without me mentioning any specific delimiter. How does that happen?

streams don't know anything about delimiters. What is happening is that, on each loop iteration, you are calling ss >> x to read the next available non-whitespace substring and convert it to an integer, and then you are calling ss >> ch to read the next available non-whitespace character following that integer. The code doesn't care what that character actually is, as long as it is not whitespace. Your loop runs until it reaches the end of the stream, or encounters a reading/conversion error.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770