2014-04-11 32 views
-1

每当我调用这个函数时,它跳过它里面的fgets语句。函数调用跳过函数的语句

void getString(char *str){ /* Read a string from the keyboard */ 
    fprintf(stdout,"Please enter a string: "); 
    fgets(str,MAX_STRING_LEN,stdin); 
} 

这里的函数调用

if(strcmp(cmd,"new")==0){ /* new string command */ 
     getString(current); 
} 
+2

你确定它已被调用?什么是“当前”?你认为它不是因为调试器(内联?)或因为它不输出任何东西而被调用? –

+2

@haccks我相信你的意思是输出? Flushing'stdin'是UB。 –

+0

@FilipeGonçalves;哎呀!删除我的评论:) – haccks

回答

1

你可能混合使用的scanf()的其他地方在你的程序,并与fgets()。对于所有输入,始终使用fgets(),如果必要的话,使用sscanf()将字符串转换为其他数据类型。

参见描述该进一步详细地comp.lang.c FAQ:

http://c-faq.com/stdio/scanfinterlace.html

0

的fprintf中的输出(3)的缓冲。在尝试读取输入之前,需要刷新该缓冲区以强制执行提示。 stderr频道通常是无缓冲的,因此您可以在不手动刷新的情况下写入该频道。