Exit out of a loop after hitting enter in c

2020-07-29 06:58发布

How should i exit out of a loop just by hitting the enter key: I tried the following code but it is not working!

  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;
    }

I have to take input as follows:

3//No of inputs
3 4 5//input 1
6
4 3//input 2
5
8//input 3
9

标签: c input
4条回答
来,给爷笑一个
2楼-- · 2020-07-29 07:28

When the program comes out of while loop, c contains '\n' so next time the program cannot go inside the while loop. You should assign some value to c other than '\n' along with j=0 inside for loop.

查看更多
smile是对你的礼貌
3楼-- · 2020-07-29 07:29

change

j=0;

to

j=0;c=' ';//initialize c, clear '\n'
查看更多
欢心
4楼-- · 2020-07-29 07:32

Your best bet is to use fgets for line based input and detect if the only thing in the line was the newline character.

If not, you can then sscanf the line you've entered to get an integer, rather than directly scanfing standard input.

A robust line input function can be found in this answer, then you just need to modify your scanf to use sscanf.

If you don't want to use that full featured input function, you can use a simpler method such as:

#include <stdio.h>
#include <string.h>

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;
}
查看更多
Root(大扎)
5楼-- · 2020-07-29 07:43

There is a difference between new line feed (\n or 10 decimal Ascii) and carriage return (\r or 13 decimal Ascii). In your code you should try:

    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;
    }

You also should note that your variable c was not initialized in the first test, if you don't expected any input beginning with '\n' or '\r', it would be good to attribute some value to it before the first test.

查看更多
登录 后发表回答