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.
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>usingnamespace 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;
}
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
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??
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.
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