首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

scanf的有关问题

2012-03-30 
scanf的问题代码C/C++ codewhile(1) {printf(Your choose:)fflush(stdin)if(scanf(%d, &choice) !

scanf的问题
代码

C/C++ code
    while(1) {            printf("Your choose:");        fflush(stdin);        if(scanf("%d", &choice) != 1)            choice = 5;        printf("%d\n", choice);        memcpy(buf, &choice, sizeof(choice));        if((sendBytes = send(sockfd, buf, sizeof(choice), 0)) == -1) {            perror("send choice");        }        switch(choice) {            case 1:recvdirlist(sockfd);break;            case 2:recvfile(sockfd, 0);break;            case 3:recvdir(sockfd, 0);break;            case 4:cliexit(sockfd);break;            default:printf("Please a number from 1-4 to represent your choice\n");        }    }


当我第一次输入数字时程序会正常执行,并且之后等待第二次输入
当我第一次输入字符/浮点数其他非数字时,之后的循环中scanf一直被跳过,程序死循环输出

Please a number from 1-4 to represent your choice
Your choose:5
Please a number from 1-4 to represent your choice
Your choose:5
Please a number from 1-4 to represent your choice
Your choose:5
Please a number from 1-4 to represent your choice
Your choose:5
Please a number from 1-4 to represent your choice
Your choose:5^C
......

GDB单步调试时情况为
C/C++ code
Breakpoint 1, main (argc=2, argv=0xbffff2f4) at ftpcli.c:8181            if(scanf("%d", &choice) != 1)(gdb) cContinuing.Your choose:a5Please a number from 1-4 to represent your choiceBreakpoint 1, main (argc=2, argv=0xbffff2f4) at ftpcli.c:8181            if(scanf("%d", &choice) != 1)(gdb) s82                choice = 5;(gdb) s83            printf("%d\n", choice);(gdb)


显然是根本就不鸟我后来的scanf
请问这是什么情况啊?

[解决办法]
http://wenku.baidu.com/view/7c46430c6c85ec3a87c2c57c.html
探讨

刷新流···
fflush(stdin)

热点排行