user2227862
user2227862

Reputation: 605

Exit out of a loop after hitting enter in c

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

Upvotes: 1

Views: 11332

Answers (4)

Ramsharan
Ramsharan

Reputation: 2064

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.

Upvotes: 0

BLUEPIXY
BLUEPIXY

Reputation: 40155

change

j=0;

to

j=0;c=' ';//initialize c, clear '\n'

Upvotes: 0

D&#233;cio Soares
D&#233;cio Soares

Reputation: 125

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.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882606

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

Upvotes: 2

Related Questions