Favolas
Favolas

Reputation: 7243

C stop at enter key

I'm learning C in ansi c and I have a question.

I what to stop reading from the console when the user prints enter.

Ideally the user will enter this

1 2 3 4 5

and right after typing 5 the program would output

1
2
3
4
5

I have this code:

#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

int main()
{
    int vector[SIZE] = {0}, number, counter = 0,i;

    while (scanf("%d", &number) != EOF  && counter < SIZE){
        vector[counter] = number;
        counter++;
    }

    for (i = 0; i < counter; i++){
        printf("%d\n", vector[i]);
    }

    return 0;
}

Now, the program if I input 1 2 3 4 5 and then hit ENTER, it does not stop and if I type 1 2 3 4 5 6 it program stops.

Two things.

I believe the condition to scan until EOF it's not doing nothing. Second, program stops just because the counter < SIZE

So, how can I stop after user hits enter?

thanks

Upvotes: 2

Views: 4733

Answers (3)

John Bode
John Bode

Reputation: 123468

Here's one approach off the top of my head (warning, untested):

int number;
char nl = 0;

while (counter < 5 && scanf("%d%c", &number, &nl) != EOF)
{
   ...
   /**
    * If we picked up a newline, exit the loop.
    */
   if (nl == '\n')
     break;
}

Upvotes: 1

Sam DeHaan
Sam DeHaan

Reputation: 10325

One option is to swap the order of your conditions:

while (counter < SIZE && scanf("%d", &number) != EOF){

As the conditions are evalulated left-to-right, your program waits for new input (via scanf(%d...)) before it evaluates counter < SIZE. This change would cause the program to immediately exit the while loop after the 5 is typed, BEFORE a user presses enter, as it evaluates counter < SIZE after the 5 is processed.

(If you choose this option, you will also want to print an endline character before you begin to repeat the numbers, as the user will not have pressed enter before it begins printing)


If you want the program to exit the loop when the user presses enter, you'll have to change your scanf. scanf(%d... reads a digit, and an endline character is not a digit.

Upvotes: 3

adelbertc
adelbertc

Reputation: 7320

Try checking the last character of input to see if its a \n. ENTER does not constitute EOF, it generally is a \n character.

Upvotes: 0

Related Questions