我写了一个简单的程序,其中包含一个计算圆的面积的函数.该程序还询问用户是否要再次计算它并且如果输入是'N'
,则该程序应该停止.
这是缩小的测试用例:
#include#include int main(void) { float r; char f; do { printf("Type the radius\n"); scanf("%f", &r); printf("Repeat? [Press N for stop]"); scanf("%c", &f); } while(f != 'N'); getch(); return 0; }
但循环永远不会像预期的那样停止.
你有什么建议吗?
scanf("%c", &f);
在输入流中留下换行符,在下一次迭代中使用该换行符.在格式字符串中添加一个空格,告诉scanf()忽略空格.
scanf(" %c", &f); // Notice the space in the format string.