Reputation: 163
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
Reputation: 212949
Use the return value from scanf:
int data;
while (1) {
int n = scanf("%d", &data);
if (n != 1)
break;
// ...
}
Upvotes: 2
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