Program to count number of words

Im trying to write a program to count number of words in a sentence. But whatever I input I always get the answer as 1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char str[80];
int count=01;
cout<<”Enter a string”;
cin>>str;
int len=strlen(str);
for(int i=0;i<len;i++)
{
if(str*i+==’ ‘)
{
count++;
}
}
cout<<”\n the no of words in a given line is “<<count<<endl;
getch();
}

The first thing to do is upgrade your compiler.

> #include<iostream.h>
Obsolete since 1998.

> #include<conio.h>
Obsolete since 1990, when the world stopped using DOS as a primary operating system.

> #include<string.h>
This is a C header, not a C++ header.

> void main()
This has never been valid.
main has always returned an int.

> cin>>str;
This always stops at the first white-space anyway, so by definition, it is always exactly one word.

Use getline() if you want to read a whole line.

Topic archived. No new replies allowed.