C++ Program to Count Number of Words in String

Here you will get C++ program to count number of words in string.

First we initialize a counter variable to 1. Now iterate through string and count all the spaces, for each space increase the value of counter. Finally print the counter variable, it contains the number of words.


Enter a string:how are you buddy?

There are 4 words in the given string

10 thoughts on “C++ Program to Count Number of Words in String

    1. Neeraj Mishra

      I dont think there is any mistake in the logic that I have used in above program. You are telling wrong logic, please check it again.

      1. babli

        one syntax error

        this should be like this

        for(int i = 0; a[i] != ‘\0’; ++i)

  1. Joseph Francis Pellissery

    Try this…(for geany IDE)

    using namespace std;

    int main( )
    char str[80];
    int flag=0;
    cout << "Enter a string: ";

    int words = 0;

    for(int i = 0; str[i] != '\0'; i++)
    if ((str[i] == ' '||str[i]==',')&&flag==0)
    else if(str[i]!=' '&&str[i]!=',')
    flag=0 ;

    cout << "The number of words = " << words+1 << endl;

    return 0;

  2. Haris Javed

    I think this is not a true program for counting the no. of words in a string.
    The reason behind is that, if we give a space or more spaces after the string ends, it gives wrong answer.


Leave a Reply

Your email address will not be published. Required fields are marked *