help_needed
help_needed

Reputation: 163

Detect when scanf got no input

I'm new to C and couldn't have the answer after some research.

I have a while loop that I want to terminate if I input nothing (hit enter) to scanf(). The below doesn't work...

int data;
while(1){
    scanf("%d", &data);
    if data == NULL{
        break;
    }
}

Upvotes: 2

Views: 14108

Answers (2)

Paul R
Paul R

Reputation: 212949

Use the return value from scanf:

int data;
while (1) {
    int n = scanf("%d", &data);
    if (n != 1)
        break;
    // ...
}

Upvotes: 2

chux
chux

Reputation: 153367

Use fgets()/sscanf()

int data;
char buf[40];
while (fgets(buf, sizeof buf, stdin) != NULL) {
  if (sscanf(buf, "%d", &data) != 1) break;
  // do stuff with data
}

Upvotes: 0

Related Questions