Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to count words in a string with C++

3 Answers

0 votes
#include <iostream>
#include <sstream>
#include <string>
 
int countWords(const std::string& s) {
    std::istringstream stream(s);
    std::string word;
    int count = 0;
 
    while (stream >> word) {
        count++;
    }
 
    return count;
}
 
int main() {
    std::string input = "C++ string parsing";
    int wordCount = countWords(input);
 
    std::cout << "Word count: " << wordCount << std::endl;
}
 
 
  
/*
run:
  
Word count: 3
  
*/

 



answered Feb 25, 2017 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
 
using std::string;
using std::vector;
 
int countWords(string s) {
    std::istringstream iss(s);
    
    vector<string> tokens{ std::istream_iterator<string>{iss},
                           std::istream_iterator<string>{} };
 
    return tokens.size();
}
 
int main()
{
    string s = "C++ string parsing";
 
    std::cout << countWords(s) << std::endl;
}
 

/*
run:
 
5
 
*/

 



answered Feb 25, 2017 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
#include <iostream>
#include <sstream>
 
int countWords(const std::string& s) {
    std::stringstream ss(s);  
    std::string word; 
    
    int count = 0; 
    while (ss >> word) {
        count++;
    }

    return count;
}
 
int main() {
    std::string input = "C++ string parsing";
    int wordCount = countWords(input);
 
    std::cout << "Word count: " << wordCount << std::endl;
}
 
 
  
/*
run:
  
Word count: 3
  
*/

 



answered Nov 1, 2025 by avibootz
...