The function char *gets(char *buffer)
reads a line from stdin and puts it into array of char
pointed to by buffer.
It stops when either the newline character is read or when the end-of-file is reached, whichever comes first.
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> int main() { char buffer[50] = { 0 }; /* Initialize buffer */ /* Loop until the user enters q or Q */ while (buffer[0] != 'q' && buffer[0] != 'Q') { /* Get coefficients */ printf("\nEnter a b c: "); scanf(" %lf %lf %lf", &a, &b, &c); gets(buffer); /* eat the end of line */ /* future code goes here */ /* prepare for next set of coefficients */ printf("Hit enter to continue, q enter to quit: "); gets(buffer); } printf("Bye!\n"); }
The input buffer is made big enough to hold whatever the user might reasonably enter. It is initialized so that the first character is 0. (The rest of the characters don't matter.) Then the loop runs as long as the first character is not 'q' or 'Q'.
Recall that scanf()
reads characters from the input stream until the pattern inside quotes is matched.
Then it stops.
Our pattern consists of three floating point numbers.
scanf()
will stop after the last number, leaving the rest of the line unread.
The gets()
that follows clears out the rest of what the user entered, including the final end-of-line.
At the bottom of the loop the user is prompted to end the program or continue.
Although the user is instructed to either hit "enter" or type 'q' and hit "enter", it is best to read in a full line:
everything up through the end-of-line character.
This is where gets()
is useful.
If the user enters a 'q' or 'Q' that will be the first character in the buffer and the loop will end.
If the user enters just "enter" then that will be the first character and the loop will continue.
Using a fixed-size buffer with gets()
would be a security risk if unauthorized user were somehow able to run this program
on your computer. For this reason, VC++ will suggest that you use its non-standard function gets_s()
. Do that, if you want.
What happens if the user enters "quit" ?