Home > Software engineering >  How can I fix my C program? The program is supposed to get the number of spaces in a string with a
How can I fix my C program? The program is supposed to get the number of spaces in a string with a

Time:01-31

Code:

#include <iostream>
#include <string>
using namespace std;

/**
   Gets the number of spaces in a string.
   @param str any string
   @return the number of spaces in str
*/

string count_spaces(string hi) {
   int spaces;
   for (int i = 0; i < hi.length(); i  ) {
      if (hi.substr(i, 1) == " ")
          spaces  =1;
   }
   return spaces;
}

int main()
{
   string str;
   getline(cin, str);
   cout << count_spaces(str) << endl;
   return 0;
}

I'm not sure why I am getting this error in my C program. spaces is an int value in the program.

Error: helper_function.cpp: In function ‘std::string count_spaces(std::string)’:
helper_function.cpp:17:8: error: could not convert ‘spaces’ from ‘int’ to ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’}
   17 | return spaces;
      |        ^~~~~~
      |        |
      |        int

I'm not sure how to go about solving it.

CodePudding user response:

you need

int count_spaces(string hi) 

instead of

string count_spaces(string hi) 

CodePudding user response:

Your count_spaces() function is declared to return a string instead of an int. You need to fix that:

int count_spaces(string hi)

Also, you need to initialize spaces, otherwise the code has undefined behavior when hi is empty since it will be returning an indeterminate value:

int spaces = 0;

Also, if (hi.substr(i, 1) == " ") can be simplified to if (hi[i] == ' '), and spaces =1; simplified to spaces;.

Although, you should consider using the standard std::count() algorithm instead of counting characters manually:

#include <algorithm>

...

size_t count_spaces(string hi) {
   return count(hi.begin(), hi.end(), ' ');
}
  • Related