0

I'm just learning c++. I have a problem with my program. I have to write a program which reverse string and count amount word in the string. My program doesn't return amount words and reverse only last word in string. I totally don't know how to correct it. :D

#include <iostream>

using namespace std;

void reverseString(string str)
{
   for (int i=str.length()-1; i>=0; i--)
   {
      cout << str[i];
    }
}

void countString(string strg)
{
    int word = 1;

    for(int j = 0; strg[j] != '\0'; j++)
    {
        if (strg[j] == ' ')
        {
            word++;
        }
    }
}

int main(void)
{
    string inputString;
    cout << "Give a string: ";
    cin >> inputString;
    cout << "Reverse string: ";
    reverseString(inputString);
    cout << "\nCounts words in a string:  ";
    countString(inputString);
    return 0;
}
stickyjack
  • 39
  • 5
  • 2
    `countString()` doesn't return nor display anything, that's why *it seems* it does nothing – Cid May 12 '20 at 10:06
  • Does this answer your question? [std::cin input with spaces?](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) – Cid May 12 '20 at 10:10

2 Answers2

2

If you want to read multiple words then you must use getline as >> reads only a single word.

string inputString;
cout << "Give a string: ";
getline(cin, inputString);

To return something from a function you must 1) specify the return type and 2) use a return statement to return a value and 3) do something with that return value in the calling function

Step 1

int countString(string strg) // here we say countString returns an integer
{
    ...
}

Step 2

int countString(string strg)
{
    ...
    return words; // here we say the value we want to return
}

Step 3

// here we output the value returned from the function
cout << "\nCounts words in a string:  " << countString(inputString) << "\n";

Knowing how to write functions that return values is absolutely fundamental C++. You should practise this. See if you can do the same with your reverseString function, instead of printing a string make it return a string.

john
  • 85,011
  • 4
  • 57
  • 81
0

There are some mistake in your code.In countString() function you return nothing.So it does not print anything.If you take input as a string include a space character,please use getline(cin, inputString).Here the code for you:

#include <iostream>

using namespace std;

void reverseString(string str)
{
   for (int i=str.length()-1; i>=0; i--)
   {
      cout << str[i];
    }
}

int countString(string strg)
{
    int word = 0;

    for(int j = 0; strg[j] != '\0'; j++)
    {
        word++;
    }
    return word;
}

int main(void)
{
    string inputString;
    cout << "Give a string: ";
    getline(cin, inputString);
    cout << "Reverse string: ";
    reverseString(inputString);
    cout << "\nCounts words in a string:  ";
    cout<<countString(inputString)<<endl;
    return 0;
}
Shakib hasan
  • 93
  • 1
  • 7