开发者

Comparing to a string literal in a console application

开发者 https://www.devze.com 2023-03-14 10:01 出处:网络
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?

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:

  1. Why are you using string? Use char instead:

    char ans; if (ans == 'Y') { // op } else if (ans == 'N') { // op }

  2. Why are you using "break" inside else if. A break statement may only be used within a switch or loop.

  3. [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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号