Harry
Harry

Reputation: 55

How to scan input data in c?

I have a case, I want to make a loop that will stop when the user enters the number 0, in that loop i want to do two things:

  1. If the user wants to add data, then the user must enter the number "1" and followed by the data (float), example: 1 2
  2. if the user wants to delete the data, the user must enter the number "2", without the accompaniment of any data thereafter. example: 2

example of user inputs:

1 5

1 3

2

0

C code that I have written is like this:

while(option != 0){
    scanf("%d %f",&option,&b);
    if(option == 1){
        Add(&Q,b);
    }else if(option == 2){
        Del(&Q,&b);
    }
}

But I have a problem, when I want to delete the data, I have to enter the number "2", only "2", but because of this part of the code:

scanf("%d %f",&option,&b);

i can't do that, I still have to enter two datas (such as when I want to add the data), but in the delete option i need only input the number "2".

How to do that simply?, help me guys, thanks.

Upvotes: 2

Views: 139

Answers (2)

ameyCU
ameyCU

Reputation: 16607

You can simply input data b and option in different scanf's . Check option first and if it is 1 then only take input in b. something like this -

while(option != 0){
   scanf("%d",&option);   // but always check return of scanf
   if(option == 1){
        scanf("%f",&b);
        Add(&Q,b);
   }
   else if(option == 2){
      Del(&Q,&b);
   }
}

Upvotes: 2

Santosh A
Santosh A

Reputation: 5361

Just fetch the user input for the variable b only after checking the value of option. That is only iff option entered is 1, scanf for b

while(option != 0) {
    scanf("%d", &option);
    if (option == 1) {
        scanf("%f", &b);
        Add(&Q,b);
    } else if(option == 2) {
        Del(&Q,&b);
    }
}

Upvotes: 2

Related Questions