Gaz96
Gaz96

Reputation: 47

How to exit the scanf function if a specific value is entered?

I want the scanf to read and store some data into a number of variables. However, if the first variable, i.e., quantity is 0 then the scanf needs to exit asking for the user input, since my following while loop depends on that value, ie., quantity. If the value is non-zero then continue looping and do further work, otherwise don't.

#include <stdio.h>

struct inventory {

    int quantity, category;
    double price, soldByWeight;
    char name[20];
};

void main(void) {

    struct inventory arr[5] = { 0 };

    printf("Enter values: \n");

    for (int i = 0; i < 5; i++) {

        scanf("%d%*c%d%*c%lf%*c%lf%*c%19[^\n]", &arr[i].quantity, &arr[i].category, &arr[i].price, &arr[i].soldByWeight, arr[i].name);

        /*while (arr[i].quantity != 0) {

            do some stuff 
        }*/
    }
    return 0;
}

Sample Input 1: 21,1,1.5,1,potato

Sample Input 2: 0

Here after sample input 2 the scanf is still waiting for the input from the user if I enter 0 and press enter key. How can I exit the scanf function after I've entered 0 along with enter key. %*c is used to flush the commas used in the sample input.

Upvotes: 1

Views: 657

Answers (2)

jyotesh
jyotesh

Reputation: 340

You can read the whole line using fgets. Then break out of the for loop if the line contains only 0. Otherwise, parse the fields using sscanf.

#include <stdio.h>

struct inventory {

    int quantity, category;
    double price, soldByWeight;
    char name[20];
};

int main() {
    struct inventory arr[5] = { 0 };

    char buf[2048];

    printf("Enter values: \n");

    for (int i = 0; i < 5; i++) {

        fgets(buf, sizeof(buf), stdin);
        if ((buf[0] == '0') && ((buf[1] == '\n') || ((buf[1] == '\r') && (buf[2] == '\n')))) {
            break;
        }

        sscanf(buf, "%d,%d,%lf,%lf,%19[^\n]", &arr[i].quantity, &arr[i].category, &arr[i].price, &arr[i].soldByWeight, arr[i].name);
        printf("%d %d %lf %lf %s\n", arr[i].quantity, arr[i].category, arr[i].price, arr[i].soldByWeight, arr[i].name);
    }
    return 0;
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409482

First of all I recommend that you read whole lines of input into a string.

Then use sscanf to parse the string, and always check what it returns.

Finally, if sscanf returns 1 then check arr[i].quantity to see if its value is zero or not.

As an alternative you could also to a pre-check for the input 0 (before calling sscanf) by using e.g. strtol.

Upvotes: 2

Related Questions