Text analyzer and modifier

Im having troubles getting my function to work.

(2) Complete the GetNumOfSpaces() function, which returns the number of spaces in the user's string. (2 pts)

(3) In main(), call the GetNumOfSpaces() function and then output the returned result. (1 pt)

(4) Implement the OutputWithoutWhitespace() function. OutputWithoutWhitespace() outputs the string's characters except for white spaces (spaces, tabs). Note: A tab is '\t'. Call the OutputWithoutWhitespace() function in main(). (2 pts)


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
 #include <iostream>
#include <string>
using namespace std;

const string usrStr;
int result = 0;
//Returns the number of  spaces in usrStr
int GetNumOfSpaces(const string usrStr) {
    int i = 0;
   for (i = 0; i < usrStr.length(); ++i) {
      if (usrStr.at(i) == ' ') {
         result = result + 1; 
      }
   }
   return result;
   
}

int main() {
const string usrStr;
cout << "Enter a sentence or phrase: " << endl;
getline (cin, usrStr);
cout << "You entered: " << usrStr << endl;
cout << GetNumOfSpaces(usrStr);
   return 0;
}
1.
const string usrStr;

Should be :
string usrStr;

2.
int i = 0;

Should be :
int i = 0; result = 0;

3. You should not use global variables, like 'result'.
i get these errors:

main.cpp: In function 'int GetNumOfSpaces(std::string)':
main.cpp:9:34: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (i = 0; i < usrStr.length(); ++i) {
Last edited on
They are not errors, they are warnings.
for (i = 0; i < usrStr.length(); ++i) {
Should be :
for (i = 0; i < (int)usrStr.length(); ++i) {
You are right, warnings. Thanks, that worked!
Topic archived. No new replies allowed.