Home > Enterprise >  stringstream in cpp is continual parsing possible
stringstream in cpp is continual parsing possible

Time:12-21

I've got a vector of strings wherein if the 1st character is "1" then I need to push the integer (represented as a string) into a vector else I just need to print the 1st char. While using stringstream the following is the code ive written.

vector<string> arr = {"1 23", "2", "1 45", "3", "4"};
vector<int> v;
for(string x : arr){
    stringstream ss(x);
    string word;
    string arr[2];
    int i =0 ;
    while(ss >> word){
        arr[i  ] = word;
    }
    i = 0;
    if(arr[0] == "1")
        v.push_back(atoi(arr[1]));
    else
        cout << arr[0] << endl;

Instead of using an array arr, is there a way to take the next word from stringstream once the first word is "1"? Because when I tried the stringstream began all over again from start.

CodePudding user response:

Assuming the strings are always well-formed and in the format you describe, and the numbers in the strings are always valid integers, you could so something like this instead:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
    const vector<string> arr = {"1 23", "2", "1 45", "3", "4"};
    vector<int> v;
    for (const string& s : arr) {
        if (s.size() > 2 && s[0] == '1' && s[1] == ' ') {
            v.push_back(atoi(s.c_str()   2));
        } else {
            cout << s << "\n";
        }
    }
    for (const int i: v) {
        cout << i << "\n";
    }
}

For strings in the array that don't start with a 1 and a space that you said you're just supposed to print, I just printed out the whole string instead of its first character.

If you're not sure about your strings in the array, you'll need to check for errors first. Also, see How can I convert a std::string to int? for alternatives to atoi().

CodePudding user response:

The code uses std::stringstream, but it doesn't take any advantage from this object, like extracting directly an int.

std::vector<std::string> arr = {"1 23", "2", "1 45", "3", "4"};
std::vector<int> v;

for ( auto const& word : arr )
{
    std::stringstream ss{ word };    // Initialize with a string,
    int first;
    if ( ss >> first )
    { // ^^^^^^^^^^^                    but extract an int...
        if ( first == 1 )
        {
            int second;
            if ( ss >> second )      // and another.
                v.push_back(second);
        }
        else
            std::cout << first << '\n';
    } // Error handling is left to the reader.
}
  • Related