How do count the amount of words in a string?
May 8, 2013 at 12:35am UTC
How can I make the program read what the user typed in and print out the amount of words in the phrase the user entered. Also, after you hit yes to play again, it skips over taking in the first phrase and goes straight to the second. Why?
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#include <iostream>
#include <string>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
char response;
int value = 0;
char msg1[80] = "" ;
char msg2[80] = "" ;
do
{
cout << "Enter a phrase: " ; //get phrase one
cin.getline(msg1, 80);
cout << "\nEnter another phrase: " ; //get phrase two
cin.getline(msg2, 80);
strtok(msg1, msg2);
cout << "\nPhrase \"" << msg1 << "\" has " << strlen(msg1) << " characters." ; //display amount of characters
cout << "\n\nPhrase \"" << msg2 << "\" has " << strlen(msg2) << " characters." ;
value = strcmp(msg1, msg2);
if (value == 0)
cout << "\n\nIn C++, phrase \"" << msg1 << "\" is equal to the phrase \"" << msg2 << "\"" ; //determine which phrase is greater
else if (value > 0)
cout << "\n\nIn C++, phrase \"" << msg1 << "\" is greater than the phrase \"" << msg2 << "\"" ;
else if (value < 0)
cout << "\n\nIn C++, phrase \"" << msg2 << "\" is greater than the phrase \"" << msg1 << "\"" ;
cout << "\n\nPlay again(y/n)? " ;
cin >> response;
response = toupper(response);
while (response != 'Y' || response == 'N' )
{
if (response == 'N' )
{
cout << "\nprogram ends." ;
break ;
}
cout << "\nEnter a valid option: " ;
cin >> response;
response = toupper(response);
}
}
while (response == 'Y' );
_getch();
return 0;
}
Last edited on May 8, 2013 at 12:49am UTC
May 8, 2013 at 5:22pm UTC
In the most basic version you shuld just loop through each character in a string, then count how many times a whitespace character was hit.
May 8, 2013 at 5:42pm UTC
Try creating a loop something like:
1 2 3 4 5 6 7 8
int b
for (a=0;a>80;a++)
{
if [msgl[a]==x] //change x with the ASCII table number of white space
{
b++ //b should store the number of spaces
}
}
I'm not sure if this works but it is what i would do.
Hope it helps
May 9, 2013 at 5:25am UTC
loop from first index to theString.lenght()
if( theString[index] == ' ' )
words++;
make sure you initialize int words to 1
Topic archived. No new replies allowed.