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?
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.
Have you initialized the integer to 0 before the scanf?
What about this?
char s[50];
fgets(s, 50, stdin);
if(s[0] != '\n') {
fentry[found].producer = atoi(s);
}
You have to remove all spaces from s though.
scanf("%29s", fentry[found].producer); while('\n'!=getchar());
This works at all, is strictly ANSI C conform, max. portable. Input buffer is cleared, chararray-length is supported, chararray contains ever a (terminating) '\0' (no initialization needed) and your array contains never the '\n' from user input.
I suspect the keyboard buffer is causing the problems in your code. The first time you call the code, it will read a maximum of 30 characters - so long as they are not the NEWLINE character. They will terminate when they read the NEWLINE. The NEWLINE will remain in the buffer.
However... if you call scanf in the same way again, the NEWLINE from the previous call will still be in the keyboard buffer. This will be read before requesting more input from the keyboard. The NEWLINE will immediately fail the scanf pattern, the char array will not be updated, and you will be left to a char pointer that points to an uninitialized area of memory.
精彩评论