Homework problem.

I've to count number of words in a string.. so all i'm doing is checking for spaces and increasing it by 1 whenever the condition evaluates to true.
But this program prints the value of count as 1 every time no matter what. What's wrong in this code? Using Visual Studio btw.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include<iostream>
using namespace std;
int main()
{
	int count=1;
	char boom[100];
	cout<<"Enter string"<<endl;
	cin>>boom; 
	
	
	for(int i=0; i<strlen(boom); i++)
	{
if(boom[i]==' ')

		count++;

	}

	cout<<"number of words are: "<<count<<endl;
return 0;
}




Last edited on
I think someone in your class is also online:
http://www.cplusplus.com/forum/beginner/110346/
when you use cin>>boom, it only reads to the first whitespace, not to the '\0'. This is why you are always getting 1. Try using std::string and std::getline instead.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<string>
using namespace std;
int main()
{
    int count=1;
    string boom;
    cout<<"Enter string"<<endl;
    getline(cin, boom);

    for(int i=0; i<boom.size(); i++)
    {
        if(boom[i]==' ')
            count++;
    }

    cout<<"number of words are: "<<count<<endl;
    return 0;
}
Last edited on
You may also want to add in some code there for multiple spaces, spaces after punctuation and trailing/ending spaces. For example, in Stewbond's code (which is a good way of doing this btw):

"This will give an answer of seven." <-- Correct
" This will give an answer of eight!" <-- Not correct!
"This will... Give an answer of eight!" <--- Also not correct
Last edited on
Stewbond, Thanks , But I know how to do it by using strings, but the thing is my professor doesn't want me to use strings. So is there any way to do it using C-style strings??
I get frustrated every single time I have to deal with C, but it will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

int main()
{
    int i, count = 1;
    char boom[100];

    printf("Enter string\n");
    scanf("%100[^\n]", boom);

    for (i = 0; boom[i] != '\0'; i++)
    {
        if( boom[i] == ' ')
            count++;
    }
    printf("number of words are: %d\n", count);
    return 0;
}
Last edited on
when you use cin>>boom, it only reads to the first whitespace, not to the '\0'.


Yes, in place of cin>> it should be gets_s(boom). That helped me understand the concept of stoneage strings.
Thanks Stewbond. :) It'd be great if you'll take look at my new question about the abort() debug error.
in place of cin>> it should be

You could use this instead:
cin.getline(boom, 100);
char boom[100];
scanf("%100[^\n]", boom);

yet another C catch: it needs to be %99[^\n] or boom[101]: the width specifier tells how many bytes to consume from the stream, but %[ (and %s) always writes one more byte for the null terminator
Topic archived. No new replies allowed.