为什么这会造成死循环?

12 views
Skip to first unread message

鸡肉男

unread,
Jun 7, 2008, 4:54:54 PM6/7/08
to c语言基地
void main()
{
int x;
printf("please input the password:\n");
scanf("%d",&x);
while(x!=100)
{
printf("you r wrong,please try again:\n");
scanf("%d",&x);
}
printf("right codes,passed");
}
这个小程序在输入字符时就会死循环,有谁知道原因没。输入的字符不时会转化为ASCII码么,跟整型的没什么差别的啊~~

Guanqun Lu

unread,
Jun 13, 2008, 3:37:01 AM6/13/08
to hy...@googlegroups.com, hell...@gmail.com
2008/6/8 鸡肉男 <hell...@gmail.com>:

你使用的是scanf("%d", &x)当然有问题了。
如果你需要读入字符的话,请使用scanf("%c", &ch); 如果需要字符串的话,那就是用scanf("%s", str);

建议你翻翻一般的C语言编程书籍。

>
> >
>

--
Guanqun

Apull

unread,
Jun 14, 2008, 8:13:59 AM6/14/08
to c语言基地
int 是2个字节
char 是一个字节,他们是不同的。
虽然char可以转为int,不过int转为char有时就需要截断,那样就会出错、

cn-batch

unread,
Jun 14, 2008, 1:14:51 PM6/14/08
to hy...@googlegroups.com
也不一定是两个字节吧,现在大多数编译器都是4字节的。
而且信息存放在低位,即便截断之后仍然是保留了低位的信息,最终,有效信息保持不变。

不仅在这个程序,大多数程序都会造成错误,例如循环的话会死循环(几乎都存在这个问题)。
所以应该不是截断的问题,而是C库runtime的问题。

Guanqun Lu

unread,
Jun 15, 2008, 1:12:34 AM6/15/08
to hy...@googlegroups.com, cnb...@gmail.com
2008/6/15 cn-batch <cnb...@gmail.com>:

> 也不一定是两个字节吧,现在大多数编译器都是4字节的。
> 而且信息存放在低位,即便截断之后仍然是保留了低位的信息,最终,有效信息保持不变。
>
> 不仅在这个程序,大多数程序都会造成错误,例如循环的话会死循环(几乎都存在这个问题)。
> 所以应该不是截断的问题,而是C库runtime的问题。

C库runtime问题?
这里完全是不明白scanf用法而导致的问题。

你可以试试看scanf("%d", &x);而你输入a回车试试看,此时scanf()返回的是0,说明根本没有读入到x。

>
> ----- Original Message -----
> From: "Apull" <apul...@gmail.com>
> To: "c语言基地" <hy...@googlegroups.com>
> Sent: Saturday, June 14, 2008 8:13 PM
> Subject: Re: 为什么这会造成死循环?
>
>
>> int 是2个字节
>> char 是一个字节,他们是不同的。
>> 虽然char可以转为int,不过int转为char有时就需要截断,那样就会出错、
>>
>> On 6月8日, 上午4时54分, 鸡肉男 <hello...@gmail.com> wrote:
>>> void main()
>>> {
>>> int x;
>>> printf("please input the password:\n");
>>> scanf("%d",&x);
>>> while(x!=100)
>>> {
>>> printf("you r wrong,please try again:\n");
>>> scanf("%d",&x);}
>>>
>>> printf("right codes,passed");}
>>>
>>> 这个小程序在输入字符时就会死循环,有谁知道原因没。输入的字符不时会转化为ASCII码么,跟整型的没什么差别的啊~~
>> >
>>
>
>
> >
>

--
Guanqun

cn-batch

unread,
Jun 15, 2008, 2:43:51 AM6/15/08
to hy...@googlegroups.com, Guanqun Lu
只能用这个方法输入字符:
scanf("%c", &x); // 仅限于单个字符
i = (int)x;
Reply all
Reply to author
Forward
0 new messages