Home > front end >  How to stop scanf with less arguments
How to stop scanf with less arguments

Time:03-11

I need to keep getting 3 values ​​(int, int, float) from the keyboard and only stop the loop when I enter 0.

The problem is that when I enter 0 and press [Enter it keeps waiting for the second and third value.

    int i, j; float v;
    while (scanf("%i %i %f", &i, &j, &v) == 3){
        Matrix* M = (Matrix*)malloc(sizeof(Matrix));
        M->line = i;
        M->column = j;
        M->info = v;
        printf("loop");
    }

I know that scanf returns an integer representing the number of successfully captured values, the question is: How to stop waiting for new inputs and return the number of already captured. (So i can exit the loop in this case.)

CodePudding user response:

I would consider just reading whole lines in the loop and then parsing that line using sscanf inside the loop. Return value 1 and the first value parsed as 0 would indicate your desired ending condition. When you had the complete line available, you could also present better error diagnostics.

CodePudding user response:

As suggested by others, would you please try:

    char line[BUFSIZ];

    while (fgets(line, BUFSIZ, stdin)) {
        if (strcmp(line, "0\n") == 0 || strcmp(line, "q\n") == 0)
            break;
        else {
            sscanf(line, "%i %i %f", &i, &j, &v);
            ...
        }
    }

Entering just 0 or q will exit the loop.

  • Related