如果用户输入q,如何退出

how to exit if user enter q

本文关键字:退出 何退出 用户 输入 如果      更新时间:2023-10-16

当用户按下Q时,它不会退出程序。。怎么了??请帮助

while (true)
{
//promt to user enter or quit
cout<<" Enter five digit number please or Q to quit n";
cin>> buf; n = atoi (buf.c_str());
cin.ignore(1000,10);
if( n == 'q' || n == 'Q')
    break;
a = n % 10;
b = n / 10000;
if ( ! a == b )
    {
    cout<< "This is not a palindrome n";
    continue;
    }
// checking the palindrome
n = n % 10;
n = n / 100;
if ( a == b )
    cout<<" This is palindromen";
else
    cout<<" This is not a palindromen";
}

如果输入'q'字符,atoi函数无法将此输入解释为数字,因此返回零。请参阅此链接

http://www.cplusplus.com/reference/cstdlib/atoi/

最重要的是以下段落:

如果str中的第一个非空白字符序列不是有效的整数,或者由于str为空或只包含空白字符而不存在这样的序列,则不执行转换并返回零

在这种情况下,str==buf

如果您在此程序中输入qQ,它将不会转换atoi中的任何内容,并且n将是0,而不是'q''Q'。如果在字符集中输入'q''Q'的数值(分别为11381),则程序将退出。

示例:

 Enter five digit number please or Q to quit 
12345
 This is not a palindrome
 Enter five digit number please or Q to quit 
12321
 This is palindrome
 Enter five digit number please or Q to quit 
q
 This is palindrome
 Enter five digit number please or Q to quit 
113 

我将把进一步的调试/修复留给你。注意,你的程序没有正确检查回文。

如前所述,q将通过atoi()转换为0。所以,基本上,为了让程序用q或q退出,在之后使用atoi()转换

if( n == 'q' || n == 'Q')
     break;

这样,当你检查程序是否应该退出时,n仍然是q或q,如果不应该,你可以用atoi()将n转换为整数,并检查它是否是回文。

希望我能帮助

尝试更改

if( n == 'q' || n == 'Q')

if( buf[0] == 'q' || buf[0] == 'Q')

这将访问输入中的第一个字符,并将其与所需字符"Q"或"Q"进行比较