如果用户输入q,如何退出
how to exit if user enter q
当用户按下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
如果您在此程序中输入q
或Q
,它将不会转换atoi
中的任何内容,并且n
将是0
,而不是'q'
或'Q'
。如果在字符集中输入'q'
或'Q'
的数值(分别为113
或81
),则程序将退出。
示例:
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"进行比较
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何让LLDB在成功时退出,在失败时等待
- C++控制台应用程序阻止退出
- 程序在执行程序的其余部分之前退出
- 构造函数在退出函数时无法初始化一个参数
- 为什么异常不退出程序?
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 退出简单while循环时出现问题
- 使用vscode调试时,GDB意外退出
- pclose() 不会给我进程退出代码
- 为什么系统函数总是在C++中返回已转移的退出状态?
- C++从另一个函数退出函数
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- boost::asio::io_service 在线程中,不会在应用程序退出时退出
- 运行自定义可执行文件,QProcess 立即退出,退出代码为 1
- OpenGL 应用程序退出,退出代码为 -1073741515 (0xC0000135)
- Poco 异步通道不会在分叉进程退出时退出
- 程序启动后立即退出,退出状态为 0