How to iterate over the words of a string in C++

3 Answers

0 votes
#include <iostream>
#include <sstream>
#include <string>

int main()
{
     std::string str = "c++ c c# java python";
     std::string word;
     std::stringstream ss(str); 
  
     while (ss >> word) {
        std::cout << word << "\n"; 
     }
}
 
 
  
/*
run:
  
c++
c
c#
java
python
  
*/

 



answered Jun 5, 2021 by avibootz
edited Mar 2, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
 
using std::cout;
using std::endl;
using std::string;
using std::vector;
 
int main()
{
    string s = "c c++ java php python";
 
    std::istringstream iss(s);
    
    vector<string> tokens{ std::istream_iterator<string>{iss},
                           std::istream_iterator<string>{} };
 
    
    for (string s : tokens) {
        cout << s << endl;
    }
}
 

/*
run:
 
c
c++
java
php
python
 
*/

 



answered Mar 2, 2025 by avibootz
0 votes
#include <iostream>
#include <sstream>
#include <iterator>
#include <string>

int main() {
     
    std::string s = "c c++ java php python";
    std::istringstream iss(s);
    
    copy(std::istream_iterator<std::string>(iss),
         std::istream_iterator<std::string>(),
         std::ostream_iterator<std::string>(std::cout, "\n"));
}
 
 
/*
run:
 
c
c++
java
php
python
 
*/

 



answered Mar 2, 2025 by avibootz

Related questions

1 answer 142 views
1 answer 97 views
97 views asked Mar 9, 2025 by avibootz
2 answers 202 views
1 answer 166 views
1 answer 196 views
1 answer 190 views
...