Linux论坛's Archiver

《开源》旗舰电子杂志2008年11期发布,火热下载中!

nlcj_linuxmine 发表于 2008-3-18 15:46

程序运行的怪现象

程序运行的怪现象, 程序如下
      1 #include <sys/ioctl.h>
      2
      3 int kbhit()
      4 {
      5     int i;
      6     ioctl(0, FIONREAD, &i);
      7     return i;
      8 }
      9
     10 int main(void)
     11 {
     12     int n = 0;
     13     int c = ' ';
     14     printf("enter 'q' to quit. \n");
     15     for(n=0; c != 'q'; n++)
     16     {
     17         if(kbhit()){
     18             system("stty raw -echo");
     19             c = getchar();
     20             system("stty cooked echo");
     21             printf("\n got %c, on iteration %d", c, n);
     22         }
     23     }
     24 }
程序的运行是:
[root@localhost Test]# ./expert_C_p185
enter 'q' to quit.
34ksdjf


got 3, on iteration 625960

got 4, on iteration 829377

got k, on iteration 953835

got s, on iteration 1105315

got d, on iteration 1204078

got j, on iteration 1296585

got f, on iteration 1420639
got

, on iteration 1521808
got

, on iteration 1688480
got

, on iteration 3013978
got

不知道为什么, n 值的输出没有按预期的效果, 而是一些很大的数!!!
源程序见 C 专家编程 185页!
望高手指点啊!!!

rose 发表于 2008-3-18 17:30

你的这句for(n=0; c != 'q'; n++)本身就是一个死循环,除非输入q,那个n肯定就会不停的增大的

nlcj_linuxmine 发表于 2008-3-18 17:52

你说“那个n肯定就会不停的增大的” 好像确实是这样的,
但是还是不太明白你的意思!
for(n=0; c != 'q'; n++)
{
}
的执行顺序不是先执行 n=0, 然后判断 c!='q', 然后是循环体吗?
接着执行n++, 然后再判断 c!='q', 然后再执行循环体, 这样循环吗?
你说“你的这句for(n=0; c != 'q'; n++)本身就是一个死循环”本身就是死循环, 不太理解, 能
说的详细些吗?  

还有, 怎样改才可以啊?

谢谢啦!  ^_~

[[i] 本帖最后由 nlcj_linuxmine 于 2008-3-18 18:07 编辑 [/i]]

rose 发表于 2008-3-18 18:06

我可能没有说清楚?你那个for里面的 if 成立的时候才打印出来n,不成立的时候n还是在++,只是没有打印出来,所以当打印出n的时候就已经++很多次了,就很大。

nlcj_linuxmine 发表于 2008-3-18 18:09

确实是这样的, 呵呵!
我一时糊涂没有看出来!
谢谢啊!

westsoftware 发表于 2008-3-18 18:09

for(n=0; c != 'q'; n++)
这个不是一个死循环。
当n为113的时候刚好是q的ASCII
n从0开始循环,N=0 然后判断c!='q'然后进入循环体
然后n++

nlcj_linuxmine 发表于 2008-3-19 09:12

[quote]原帖由 [i]westsoftware[/i] 于 18-3-2008 18:09 发表
...
当n为113的时候刚好是q的ASCII
n从0开始循环,N=0 然后判断c!='q'然后进入循环体
...
[/quote]
不理解你说的! 程序循环体中并没有对n进行初始化啊。

Flyinmorning 发表于 2008-3-19 09:49

[quote]原帖由 [i]nlcj_linuxmine[/i] 于 2008-3-19 09:12 发表 [url=http://bbs.linuxpk.com/redirect.php?goto=findpost&pid=44306&ptid=13314][img]http://bbs.linuxpk.com/images/common/back.gif[/img][/url]

不理解你说的! 程序循环体中并没有对n进行初始化啊。 [/quote]

嗯,westsoftware是看花了,呵呵

westsoftware 发表于 2008-3-19 10:55

看花了。。呵呵

nlcj_linuxmine 发表于 2008-3-19 16:37

:)    呵呵!

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.