Hi everyone,

I have a project for my class. I have to write a function that accepts 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 would return the number 6. I have worked on the project but I can't seem to put it all together to make it work.. Could someone please look it over and point to my errors and help me correct them? Appreciate the help, thank you.

// this program accepts a c-string as an argument and returns the number of words contained in the string

#include <iostream>
using namespace std;

// function prototype
int countChars(char *, char);

int main()
{
    char userString[60], words;
    cout << "enter a string (up to 60 characters): ";
    cin.getline(userString, 61);
    cin >> words;
    cout << words << " has ";
    cout << countChars(userString, words) << " words.\n";
    return 0;
}

int countChars(char *strptr, char ch)
{
    int words = 0;
    while (*strptr != '\0')
    {
        if (*strPtr == ch)
            words++;
        strPtr++;
    }
    return words;

Recommended Answers

All 5 Replies

A word is a sequence of non-whitespace characters separated by whitespace. Use a flag to indicate when you are in whitespace or not. Going from non-whitespace to whitespace would be the end of a word.

Can anybody help fix my source code or show me how to properly write this program?? I'm really at a loss here and I've been going through my books for hours and cannot figure it out... thank you.

Can you learn to enclose code within [CODE]?

[I did give fairly pointed hints cough isspace cough <cctype> cough.]

so would it be something like:

if (isspace(words))
cout << "the total number of words in the sentence is: "; << words++ << endl;

To check for the no. of words run a loop and check each character of the string. if the character is equal to a white space then words++.
the no. of words found by checking only whitespace can be one less than the actual no. of words in the string b`coz ther is no whitespace after the last word so increment the value of words by 1 before displaying the results.
GOOD LUCK.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.