Reputation: 25
So my problem goes like this:
string something (string something){
string letter;
cout << "press a";
cin >> letter;
if (letter==a){
return a;
}
else
cout << "wrong letter";
//what should I put here if I don't want it to return any value?
}
Any alternatives would also be welcome
Upvotes: 0
Views: 390
Reputation: 7798
One way to handle this would be a std::optional<std::string>
#include <optional>
std::optional<std::string> dingas(std::string something)
{
string letter;
cout << "press a";
cin >> letter;
if (letter==something){
return "a";
}
else
{
std::cout << "wrong letter";
return std::nullopt;
}
}
[1] https://en.cppreference.com/w/cpp/utility/optional
Upvotes: 3
Reputation: 234695
Consider using the exception mechanism for this: this carries the advantage that you can keep a reasonable return type, and you can also delegate handling of the exception to the caller of the function.
First, write
struct WrongLetterException : public std::exception{};
Then change the function to
std::string something (std::string something/*ToDo - is this correct?*/){
std::string letter;
std::cout << "press a";
std::cin >> letter;
if (letter == "a"/*note the change here*/){
return a;
}
throw WrongLetterException();
}
In the caller to the function, you then catch (const WrongLetterException& ex)
and deal with it as you see fit.
Upvotes: 2
Reputation: 122341
If you want to read a single character you could use a char
. However, if the function is declared to return a std::string
but you do not want to return a std::string
you have several options:
std::string
bool something(std::string& out)
such that the return value signals sucess and when it is true
the result is written to out
.std::optional<std::string>
. A std::optional<std::string>
either contains a std::string
or not.return
Which one you pick is up to you. Exceptions should be used for exceptional cases, so you need to decide if not returning is "normal" or exceptional. It will require the caller to handle the exception. bool something(std::string&)
is similarly inconvenient for the caller, because they need to check the return value and provide the string to be used. Usually a sentinal value (ie giving special meaning to the empty string) can cause problems, because one day you might confuse the sentinal with a proper return value. Though, as the function either returns a string with a single character or not, this isnt a big issue. I'd prefer the std::optional
, but thats just my biased opinion.
Upvotes: 2