C++ Program to Count no. of words in a string

C++ Program to Count no. of words in a string

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

void main()
{
clrscr();
char a[100];
int i,count=1;
cout<<“Enter a string:”;
gets(a);

for(i=0;a[i]!=’’;++i)
{
if(a[i]==’ ‘)
count++;
}

cout<<“nThere are “<<count<<” words in the given string”;
getch();
}

8 thoughts on “C++ Program to Count no. of words in a 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.

      Reply
      1. babli

        one syntax error
        for(i=0;a[i]!=’’;++i)

        this should be like this

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

        Reply
  1. Joseph Francis Pellissery

    Try this…(for geany IDE)
    ===================

    #include
    using namespace std;

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

    int words = 0;

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

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

    return 0;
    }

    Reply

Leave a Reply

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