How to tokenize a string in C++

2 Answers

0 votes
#include <bits/stdc++.h> 
    
using namespace std;

int main()
{
    string s = "c++ c java php";
    vector <string> tokens; 
      
    stringstream sst(s); 
      
    string word; 
      
    while(getline(sst, word, ' ')) { 
        tokens.push_back(word); 
    } 
      
    for(int i = 0; i < tokens.size(); i++) {
        cout << tokens[i] << endl; 
    } 
    
    return 0;
}


/*
run:

c++
c
java
php

*/

 



answered Dec 5, 2019 by avibootz
0 votes
#include <bits/stdc++.h> 
    
using namespace std;

int main()
{
    string s = "c++ c java php";

    stringstream sst(s); 
      
    string token; 
      
    while(getline(sst, token, ' ')) { 
        cout << token << endl; 
    } 

    return 0;
}



/*
run:

c++
c
java
php

*/

 



answered Dec 5, 2019 by avibootz

Related questions

1 answer 110 views
110 views asked Apr 10, 2025 by avibootz
1 answer 426 views
426 views asked Dec 5, 2019 by avibootz
1 answer 169 views
3 answers 328 views
...