但是在交互式文件中使用scanf时会遇到问题。 您还犯了致命错误,即没有检查 scanf返回值。 printf()s之后应该是 fflush(stdout); 你可以使用几个包装器处理大部分这些东西 功能: #include< stdio.h> 无效提示(char * line) { printf(line); fflush(stdout); } void getfloat(float * fv,char * promptln) { do { prompt(promptln); } while(1!= scanf("%f",fv))'' } int getonechar(char * promptln) { int ch; if(1!= scanf("%c",ch))return 0; 返回(unsigned char)ch; } / *之后你的例程减少到:* / int main() { 浮动宽度,长度,面积; do { getfloat(& width," \ nEnter Rect of the rectangle"); getfloat(& length," \\ n输入矩形的长度); area = length * width; printf(矩形的\ n区域为%.2f,区域) ; } while(''Y''== toupper(getonechar( " \ nContinue? - 输入Y代表是,N代表否))); 返回0; } 注意子程序如何简化和澄清。然而,由于 使用scanf,因此仍然存在各种令人讨厌的交互式使用问题。尝试使用2 3 Y (不带引号)回复第一个提示。 - Chuck F(cb********@yahoo.com)(cb********@worldnet.att.net) 可用于咨询/临时嵌入式和系统。 < http://cbfalconer.home.att.net>使用worldnet地址!However you will have problems using scanf in interactive files.You have also committed the fatal mistake of not checking thescanf return value. The printf()s should be followed byfflush(stdout);You can handle most of these things with a couple of wrapperfunctions:#include <stdio.h>void prompt(char *line){printf(line);fflush(stdout);}void getfloat(float *fv, char *promptln){do {prompt(promptln);} while (1 != scanf("%f", fv))''}int getonechar(char *promptln){int ch;if (1 != scanf(" %c", ch)) return 0;return (unsigned char) ch;}/* after which your routine reduces to: */int main(){float width, length, area;do {getfloat(&width, "\nEnter width of the rectangle ");getfloat(&length, "\nEnter length of the rectangle ");area = length * width;printf("\nArea of the rectangle is %.2f", area);} while(''Y'' == toupper(getonechar("\nContinue? - Enter Y for yes, N for no ")));return 0;}Notice how subroutines simplify and clarify. However that stillhas all sorts of nasty problems for interactive use, because ofthe use of scanf. Try responding to the first prompt with "2 3 Y"(without the quotes) for example.--Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)Available for consulting/temporary embedded and systems.<http://cbfalconer.home.att.net> USE worldnet address! 这篇关于scanf问题(“%c”,&amp; answer);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-24 11:04