点击进入c后退出循环
如何通过按Enter键退出循环:我尝试了以下代码,但它无法正常工作!
int main() { int n,i,j,no,arr[10]; char c; scanf("%d",&n); for(i=0;i<n;i++) { j=0; while(c!='\n') { scanf("%d",&arr[j]); c=getchar(); j++; } scanf("%d",&no); } return 0; }
我必须输入如下内容:
3//No of inputs 3 4 5//input 1 6 4 3//input 2 5 8//input 3 9
最好的办法是使用fgets
进行基于行的输入,并检测行中唯一的内容是换行符。
如果没有,您可以对您输入的行进行sscanf
以获得整数,而不是直接scanf
标准输入。
在这个答案中可以找到一个强大的行输入function,然后您只需要修改您的scanf
以使用sscanf
。
如果您不想使用该全function输入function,可以使用更简单的方法,例如:
#include #include int main(void) { char inputStr[1024]; int intVal; // Loop forever. for (;;) { // Get a string from the user, break on error. printf ("Enter your string: "); if (fgets (inputStr, sizeof (inputStr), stdin) == NULL) break; // Break if nothing entered. if (strcmp (inputStr, "\n") == 0) break; // Get and print integer. if (sscanf (inputStr, "%d", &intVal) != 1) printf ("scanf failure\n"); else printf ("You entered %d\n", intVal); } return 0; }
新换行符(\ n或10十进制Ascii)和回车符(\ r或13十进制Ascii)之间存在差异。 在您的代码中,您应该尝试:
switch(c) { case 10: scanf("%d",&no); /*c=something if you need to enter the loop again after reading no*/ break; case 13: scanf("%d",&no); /*c=something if you need to enter the loop again after reading no*/ break; default: scanf("%d",&arr[j]); c=getchar(); j++; break; }
您还应注意,您的变量c未在第一次测试中初始化,如果您不希望任何以“\ n”或“\ r \ n”开头的输入,那么在第一次测试之前将某些值归于其中会更好。
更改
j=0;
至
j=0;c=' ';//initialize c, clear '\n'
当程序退出while
循环时, c
包含'\n'
因此下次程序无法进入while
循环时。 你应该为'\n'
以外'\n'
c
赋予一些值,同时在for
循环中给j=0
。