请帮忙看看以下程序为何陷入死循环?!
原程序如下,意为检查输入是否为1-4这4个数字字符,并将其输出(本来是一个菜单选择程序,应将所选数字返回的,我作了简化)。其中atoi函数是将字符串转换为数字:跳过前面的空格字符,直到遇上数字或下负号才开始做转换,而再遇到非数字或字符串结束时( '\0 ')才结束转换。
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
main()
{
char s[2];
int cn;
cout < < "\t1.菜单1\n ";
cout < < "\t2.菜单2\n ";
cout < < "\t3.菜单3\n ";
cout < < "\t4.菜单4\n ";
cout < < "\t选择1-4:\n ";
for(;;)
{
gets(s);
cn=atoi(s);
if(cn <1||cn> 4)
printf( "\n\t输入错误,重选: ");
else
break;
}
cout < <cn;
}
我本来觉得不用atoi函数也行,所以作了修改如下,但在输入如“+”、“{”等字符时陷入死循环,不断输出“输入错误,重选”这一提示信息,这是为什么??
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
main()
{
//char s[2];
int cn;
cout < < "\t1.菜单1\n ";
cout < < "\t2.菜单2\n ";
cout < < "\t3.菜单3\n ";
cout < < "\t4.菜单4\n ";
cout < < "\t选择1-4:\n ";
for(;;)
{
//gets(s);
cin> > cn;
//cn=atoi(s);
if(cn <1||cn> 4)
printf( "\n\t输入错误,重选: ");
else
break;
}
cout < <cn;
}
[解决办法]
呵呵,是因为cn是int所以....先不告诉你,你自己cout出来看看吧:)
[解决办法]
//gets(s);
cin> > cn;
//cn=atoi(s);
if(cn <1||cn> 4)
printf( "\n\t输入错误,重选: ");
cout < <cn; //你看看这个地方输出的是什么值.应该是ASCII码值
else
break;
[解决办法]
gets(s);
好像不读入回车,所以在下面应该弄个函数把回车接收了,比如_getch();
即:
gets(s);
_getch();
你试试看。
[解决办法]
LZ这么写吧:
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
printf( "\t1.菜单1\n ");
printf( "\t2.菜单2\n ");
printf( "\t3.菜单3\n ");
printf( "\t4.菜单4\n ");
printf( "\t选择1-4:\n ");
char ch;
scanf( "%c ", &ch);
for(; ch < '1 '||ch> '4 '; )
{
printf( "输入错误,重选: ");
scanf( "%c ", &ch);
}
printf( "您选择了: %c\n ", ch);
return 0;
}
[解决办法]
如果你一定要读取int
你可以这样写,其中原因是很清楚的
ClearError()函数是MSDN提供的
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
int ClearError(istream& isIn) // Clears istream object
{
streambuf* sbpThis;
char szTempBuf[20];
int nCount, nRet = isIn.rdstate();
if (nRet) // Any errors?
{
isIn.clear(); // Clear error flags
sbpThis = isIn.rdbuf(); // Get streambuf pointer
nCount = sbpThis-> in_avail(); // Number of characters in buffer
while (nCount) // Extract them to szTempBuf
{
if (nCount > 20)
{
sbpThis-> sgetn(szTempBuf, 20);
nCount -= 20;
}
else
{
sbpThis-> sgetn(szTempBuf, nCount);
nCount = 0;
}
}
}
return nRet;
}
int main()
{
char s[32];
int cn;
cout < < "\t1.菜单1\n ";
cout < < "\t2.菜单2\n ";
cout < < "\t3.菜单3\n ";
cout < < "\t4.菜单4\n ";
cout < < "\t选择1-4:\n ";
for(;;)
{
cin> > cn;
if(cn == 0) ClearError(cin);
if(cn <1||cn> 4)
{
printf( "\n\t输入错误,重选: ");
}
else
break;
}
cout < <cn;
return 0;
}
[解决办法]
这是由于cin读入错误造成的,解决办法如下代码:
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
void main()
{
//char s[2];
int cn;
cout < < "\t1.菜单1\n ";
cout < < "\t2.菜单2\n ";
cout < < "\t3.菜单3\n ";
cout < < "\t4.菜单4\n ";
cout < < "\t选择1-4:\n ";
char buffer[255];
for(;;)
{
//gets(s);
cin> > cn;
if (cin.fail())
{
cin.clear();// 复位标志位
cin.getline(buffer, 255);// 清空上次的输入
}
//cn=atoi(s);
if(cn <1||cn> 4)
printf( "\n\t输入错误,重选: ");
else
break;
}
cout < <cn;
}