I have a simple native C++ console app.
I want to stay something like this:Quit? (Y/N)
and be able to type in Y or N to tell the program what to do? So far I have this code:
std::string whetherTo开发者_JS百科Quit;
std::cout<<"Quit? (Y/N): ";
std::cin>>whetherToQuit;
if(whetherToQuit == "Y"){
exit(EXIT_SUCCESS);
}
else if (whetherToQuit == "N"){
break;
}
MSVC++ gives me a warning and I think there should be a better way to do this.
If it matters I am using Windows. Any suggestions?Why not use a char
instead:
char ans;
std::cout << "Quit? (Y/N): ";
std::cin >> ans;
if (ans == 'Y') {
return 0;
}
else if (ans == 'N') {
break;
}
There are three points worth mentioning:
Why are you using string? Use char instead:
char ans; if (ans == 'Y') { // op } else if (ans == 'N') { // op }
Why are you using "break" inside else if. A break statement may only be used within a switch or loop.
[ADDED] Use return instead of Exit. Exit circumvents RAII.
Final code should look like
char ans;
std::cout << "Quit? (Y/N): ";
std::cin >> ans;
if (ans == 'Y') {
return 0;
}
else if (ans == 'N') {
// No op;
}
What does the warning message say?
You can do like this:
const std::string strYes = "Y";
const std::string strNo = "N";
and then compare with this constants.
精彩评论