I want to be able to to take the user input and assign the given letter a value. I think I got that part down, now the problem is returning the value.
#include <iostream>
#include <string>
using namespace std;
int ch2n(string word);
int main()
{
string inputWord;
cout << "Type Word: ";
cin >> inputWord;
cout << ch2n(inputWord);
}
int ch2n(string word)
{
int total = 0;
for(int i = 0;i != word.size(); i++)
{
if(word.find(i) == 'a' || word.find(i) == 'A')
{
total += 1;
}
}
return total;
}
when I declare the total to 0, the return is always 0, but when I don't declare it, I get a return value of 229.... etc random number.
Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
Some functions don't return any value. (In these cases, our reference pages list the return value as void or undefined .) For example, in the displayMessage() function we built in the previous article, no specific value is returned when the function is invoked.
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
In C there are no subroutines, only functions, but functions are not required to return a value. The correct way to indicate that a function does not return a value is to use the return type "void". ( This is a way of explicitly saying that the function returns nothing. )
I think word.find(i)
is probably not what you want to call there. To access a specific character within the string, use square brackets, i.e.: word[i]
instead of word.find(i)
.
If you don't initialize it (set its value), using it is undefined behaviour and can return any random value - including 0
types without constructor, like int
will just allocate space and have an undefinedd value, generally based on whatever happens to be in that location from prior use.
word.find
does not do what you think it does, it is searching for i
in word
You want to just use word[]
:
if(word[i] == 'a' || word[i] == 'A')
Also, you might want to put std::endl
at the end of your cout
lines
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With