无限循环与do功能

时间:2012-12-12 00:44:06

标签: c++ loops do-while

我正在尝试在do while函数中运行一些代码:

do {
    printf("\nThis game has two different modes: I Guess, You Guess\n");
    Sleep(2000);
    printf("Which mode do you want to play?\n");
    cin >> mStr;
    cout << "Are you sure you want to play " << mStr << " mode?";
    cin >> choice;
} while (choice != "No");

但是,每次我输入mStr(char数组)时,它都会重新启动。它甚至没有执行cout。

以下是名为:

的char数组
char mStr[10];
char choice[4];

另外,我怎么能用printf()而不是cout呢?我正在努力练习。

编辑:

这是新代码:

do {
    printf("\nThis game has two different modes: I Guess, You Guess\n");
    Sleep(2000);
    printf("Which mode do you want to play?\n");
    cin >> mStr;
    printf("Are you sure you want to play %s mode?", mStr); //Cuts off here and doesnt display the 'Guess' part of I Guess
    cin >> choice;
} while (strcmp(cKey, choice) != 1);

2 个答案:

答案 0 :(得分:5)

您无法使用!=比较字符数组,您需要使用strcmp作为示例:

while (strcmp(choice, "No")!=0)

或只是改变:

std::string mStr;
std::string choice;

然后你可以打电话

while (choice != "No")

修改

正如Jarryd在我的评论中提到的,如果你输入超过mStr长度的字符,选择它是未定义的行为。

答案 1 :(得分:2)

绝不应将字符串与普通的等式和不等式运算符==!=进行比较。相反,你应该使用像strcmp这样的适当函数。