I need to make a Word Counter, I need to Return the number of times the character " " appears in the text.
with a function that accepts a pointer to a C-string as an argument and returns the number of words contained in the string.
•For instance, if the string argument is "Four Score and seven years ago" the function should return the number 6.
•Demonstrate the function in a program that asks the user to input a string and then passes it to the function.
•The number of words in the string should be displayed on the screen.
•Allow for sentences of up to 100 characters.
I must have all of this in the program otherwise it will be rejected:
Correct Prototype.
Correct function declaration
Returns the number of times the character " " appears in the text.
Got the word count correctly
Here is my code
I just need to return the number of times the character " " appears in the text.
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
|
#include <iostream>
#include <string>
using namespace std;
// function prototype
int numWords(char*);
int numWords(string);
int main()
{
char* myPtr = nullptr;
const int SIZE = 101;
char userSent[SIZE];
myPtr = userSent;
string sent;
cout << "Enter a sentence less than " << (SIZE - 1) << " characters" << endl;
cin.getline(myPtr, SIZE);
//getline(cin, sent);
//display the number of words contained in the user sentence
cout << "Your sentence contains " << numWords(myPtr) << " words" << endl;
return 0;
}
//======================================================================
// function definition - counts how many words are in the string that is passed as an arg
int numWords(char* sentence)
{
int totalWords = 0; // counts words
if (*(sentence) != '\0') // if some input then there is at least 1 word
++totalWords;
for (int count = 0; *(sentence+count) != '\0'; count++)
{
if (*(sentence + count) == ' ')
{
++totalWords;
}
}
return totalWords;
}
|