Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanf for question, allow user to skip question

I'm working on a final project for a C programming course. The project is to create a database to store drug information. I've completed all of the elements and now it's down to fine tuning everything.

There's a requirement in the project in the function where the user can change the drugs information. In the requirement, the user should be able to skip a field by hitting enter. For example, the user can change the producer of the drug and the quantity. If the user didn't want to change the producer, they'd hit enter and move onto the quantity.

I've looked around the internet and was able to let the user skip entering a string for the producer. However, I cannot get it work with an integer.

This is what I used so that the user can skip entering a string:

scanf("%30[^\n]", fentry[found].producer);

For clarity sake, fentry.producer is a string with 30 characters and found is an integer variable.

I've tried doing something similar with the integer input (EDIT: By integer input, I meant the one to enter the quantity, not the 'found' varible). It will let you skip entering something, but if you do enter something, it stores a random value.

Anyone know how to go about this?

like image 754
confusedstudent Avatar asked Feb 25 '26 04:02

confusedstudent


1 Answers

Rather than using scanf(), a better way to get interactive input from a user is to use fgets(). This function gets a complete line of input up to where the user presses Enter, and returns it so you can parse it.

You can then use sscanf() to read the information out of the line, if you like. sscanf() works almost exactly like scanf() except it reads data from a string rather than from standard input.

like image 179
Greg Hewgill Avatar answered Mar 02 '26 22:03

Greg Hewgill