Laura
Laura

Reputation: 27

Counting blank spaces to get word count

I have a homework assignment in which I have to return the number of words in a string based on the number of blank spaces. Here is my code, I am not sure what is wrong with it but I keep getting error messages when I try to compile it.

string getWordCount(string sentence){
    int count = 1;
    for(int i = 1; i < sentence.length(); i++){
        if (s[i]==' '){
            count++;
        }
    }
    return count;
}

The error messages are:

error: ‘s’ was not declared in this scope
     if (s[i]==' '){
         ^
error: could not convert ‘count’ from ‘int’ to ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
     return count;
            ^~~~~

Upvotes: 0

Views: 1187

Answers (4)

Brooke
Brooke

Reputation: 119

Generally, when a variable is not declared within a scope you defined it inside something locally and it does not exist after that block of code (i.e. for loop) has finished executing. Or, you have not declared the variable at all.

error: ‘s’ was not declared in this scope
     if (s[i]==' '){
     ^

Assuming you were trying to iterate through the parameter you passed in, which is a string called sentence, I either change the variable name to s of the parameter, copy the string into another string called s, or change s to sentence in the loop. The different variations are shown below:

       // change parameter name to s
       string getWordCount(string s)
      {
        int count = 1;
        for(int i = 1; i < sentence.length(); i++)
        {
            if (s[i]==' ')
                count++;
        }
        return count;
      }

      // change s to sentence inside the loop
      string getWordCount(string sentence)
      {
        int count = 1;
        for(int i = 1; i < sentence.length(); i++)
        {
            if (sentence[i]==' ')
                count++;
        }
        return count;
     }
  // create a string s, and copy sentence into string s
  string getWordCount(string sentence)
  {
    int count = 1;
    string s = strcpy(s, sentence);
    for(int i = 1; i < sentence.length(); i++)
    {
        if (s[i]==' ')
            count++;
    }
    return count;
 }

For your second error, generally this error occurs when there is an issue with casting a variable type to another type. In your case, the below error occurs because you are declaring a function will return a string, however, you are trying to return an int.

error: could not convert ‘count’ from ‘int’ to ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
     return count;
            ^~~~~

To fix this error, simply change the return type to int. However, if you really want to return the count as a string for some reason, convert the integer to a string before returning. Both variations are shown below.

// Change return type to int to match count's type
int getWordCount(string sentence)
{
    int count = 1;
    ...
    ...
    return count;
}

// If you really need to send count back as a string for some reason, convert the int to string
string getWordCount(string sentence)
{
    int count = 1;
    ...
    ...
    return itoa (count);
}

Please note: this is only describing why your compilation errors are occurring and how to fix them so that you can continue on with your homework assignment. This is not describing what is wrong, logically, with your code.

Upvotes: -1

Jive Dadson
Jive Dadson

Reputation: 17056

What they said.

Plus ...Avoid indexing with square brackets. Use range-based for loops. Be careful about trivial input (no words, or even an empty string, in this case). Do not assume that white space is only spaces, or that it only comprises one character. Input parameters that a function does not modify can be declared const-reference, to avoid making an un-needed copy. Use #include <algorithm> for common tasks.

SPOILER ALERT. Read no more until you after you have finished the assignment.

#include <cctype>
#include <string>

int get_word_count(const std::string &sentence)
{
    int count = 0;
    bool scanning_a_word = false;
    for (auto ch : sentence) {
        if (!std::isspace(ch)) {
            if (!scanning_a_word) {
                count += 1;
                scanning_a_word = true;
            }
        } else {
            scanning_a_word = false;
        }
    }
    return count;
}

Bonus (and better) solution. The following does not use a state-variable (scanning_a_word). I call that kind of code "bread crumb programming". You leave bread crumbs along the trail to show where you've been. Sometimes birds eat the bread crumbs. Look Ma, no crumbs!

#include <algorithm>
int get_word_count(const std::string &sentence)
{
    int count = 0;
    auto next = sentence.begin();
    const auto done = sentence.end();
    while(done != next) {
        next = std::find_if_not(next, done, std::isspace);
        if (done != next) {
            count += 1;
            next = std::find_if(next, done, std::isspace);
        }
    };
    return count;
}

Upvotes: 0

Christophe
Christophe

Reputation: 73627

To compile your code, you must ensure that return type (count is an int) is compatible with the declared return type of the function (you said it would return string). So instead of:

string getWordCount(string sentence)

declare your function as :

int  getWordCount(string sentence)

Note also that you use s[i], but s is not declared. You probably mean sentence[i].

Consider also solving the different algorithmic errors mentionned in the comments (i.e. wrong result for an empty string, for a string with only blank, and depending on the exercise narative, for a string where several consecutive spaces are used between two words) to finish your homework and improve your skills.

Upvotes: 3

SharpSol
SharpSol

Reputation: 46

You are passing in a variable named sentence but parsing on a variable named s. Also, count is an int but your return type is string. Try this:

int getWordCount (string sentence)
{
  int count = 1;
  for (int i = 0; i < sentence.length (); i++)
    {
      if (sentence[i] == ' ')
        count++;
    }
  return count;
}

Upvotes: 0

Related Questions