2013-08-27 45 views
0

当用户按下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 palindrome\n"; 
else 
    cout<<" This is not a palindrome\n"; 

} 

回答

0

如果输入qQ这个计划,也不会在atoi转换什么,n0,不'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 

我将离开进一步调试/固定给你。请注意 - 您的程序无法正确检查回文。

1

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

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

最重要的是以下内容:

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

在这种情况下STR == BUF

0

如在以前的答案指出,Q将被()转换为0与的atoi。所以,基本上,为了使程序与水性或Q退出,使用后

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

这种方式的atoi()转换,正仍将是q或q当检查程序应该退出,如果不是,那么你将n转换为带有atoi()的整数,并检查它是否是回文。

希望我能帮助

+0

你的意思是这样的: – Aysin

+0

if(n =='1'|| n =='1') cin >> buf; n = atoi(buf.c_str()); 休息; – Aysin

+0

uhm,no ... if(n =='1'|| n =='1')与if(n =='1')相同,因为您在两个条件相同。我的解决方案的工作方式与Ed Heal的解决方案几乎相同,所以如果解决方案能够解决问题,那么很好,解决问题 – Sampaio

0

尝试改变

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

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

这将访问的第一个字符的输入,并将其与所需的字符“Q”或'比较q'

+0

非常感谢! – Aysin

+0

@OruzAysn - 有用吗?确实是 –

+0

!非常感谢你 – Aysin

相关问题