pabloapast
pabloapast

Reputation: 75

How to use scanf in a loop to read data until a EOL?

the problem I have is as follows:

I need to create a function in C, using the standard libraries. This function should read data from standard input as follows: value1 value2 value3

Whose type is uint32_t.

The problem is that I do not like that much data going to enter, I can just finish reading the data when the user enter a line that does not respect the format given, or when entering a line with spaces or when entering an EOF.

I was reading several answers to similar problems in the page and this is the code that I did:

int main(void) {
uint32_t value1, value2, value3;
int ret = 3;
char ch;
while (true) {
    printf("Enter the data:\n");
    ret = scanf("%u %u %u", &value1, &value2, &value3);
    if ((ret != 3) || (getc(stdin) == EOF) ||
        (getchar() == ' ')) {
        break;
    }
    printf("\nYou entered: %u, %u, %u\n", value1, value2, value3);
}
printf("Finish..");
return 0;
}

But not working properly.

Any suggestions?

Upvotes: 0

Views: 1109

Answers (1)

hmjd
hmjd

Reputation: 121961

Suggest:

  • read the line using fgets()
  • read the line populated by fgets() with sscanf(), similar to how scanf() is currently used

this has the benefit of reading the line always, whereas the posted code needs to discard the line if the scanf() fails, on invalid input for example.

Example:

printf("Enter the data:\n");
char line[1024];
while (fgets(line, 1024, stdin))
{
    uint32_t values[3];
    if (sscanf(line, "%u %u %u", &values[0], &values[1], &values[2]))
    {
        printf("\nYou entered: %u, %u, %u\n", values[0], values[1], value[2]);
        break;
    }
    fprintf(stderr, "Invalid input, retry...\n");
}

Upvotes: 2

Related Questions