I need to use fgets to read multiple lines of stdin that are separated by newlines (ex.
Hello
world
!
). If I include fgets in a for loop, will it read from the first line during every iteration? If so, how would I go about achieving this?
Will fgets always read from the beginning of the string?
No. fgets() reads based on the current state, which might be partially into a line of user input. It does not somehow magically go back to the beginning - just starts from where the stream is currently positioned..
fgets() does not read strings. It read a line of input and converts the input into a string. #Fe2O3. It does not stop when a null character is read.
fgets() reads until:
An '\n' is read.
The size - 1 passed in fgets() is met.
An end-of-file or input error is encountered (e.g. wrong stream mode, parity error, phase of the moon input error, ...)
If I include fgets in a for loop, will it read from the first line during every iteration? If so, how would I go about achieving this?
First before using fgets(), be sure the entire prior line was read.
2nd: if this line of input after using fgets() was incomplete, finish it.
char buf[N];
if (fgets(buf, sizeof buf, stdin) {
size_t len = strlen(buf);
if (len + 1 == sizeof buf && buf[sizeof buf - 2] != '\n')) {
// User input is not complete, read rest of line.
int ch;
while ((ch = getchar() != '\n') ** ch != EOF) {
;
}
}
Pedantic: fgets() is not a great input function if input might include null characters. In that case, more advance techniques are needed.
I have the following program:
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
As the author of the above code have explained:
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
OK, I got this. But my first question is: Why the second getchar() (ch2 = getchar();) does not read the Enter key (13), rather than \n character?
Next, the author proposed 2 ways to solve such probrems:
use fflush()
write a function like this:
void
clear (void)
{
while ( getchar() != '\n' );
}
This code worked actually. But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'? if so, in the input buffer still remains the '\n' character?
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.
If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.
As for the proposed solutions, see (again from the comp.lang.c FAQ):
How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
If fflush won't work, what can I use to flush input?
which basically state that the only portable approach is to do:
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.
Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?
You can do it (also) this way:
fseek(stdin,0,SEEK_END);
A portable way to clear up to the end of a line that you've already tried to read partially is:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }
This reads and discards characters until it gets \n which signals the end of the file. It also checks against EOF in case the input stream gets closed before the end of the line. The type of c must be int (or larger) in order to be able to hold the value EOF.
There is no portable way to find out if there are any more lines after the current line (if there aren't, then getchar will block for input).
The lines:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
;
doesn't read only the characters before the linefeed ('\n'). It reads all the characters in the stream (and discards them) up to and including the next linefeed (or EOF is encountered). For the test to be true, it has to read the linefeed first; so when the loop stops, the linefeed was the last character read, but it has been read.
As for why it reads a linefeed instead of a carriage return, that's because the system has translated the return to a linefeed. When enter is pressed, that signals the end of the line... but the stream contains a line feed instead since that's the normal end-of-line marker for the system. That might be platform dependent.
Also, using fflush() on an input stream doesn't work on all platforms; for example it doesn't generally work on Linux.
But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character???
Am I misunderstanding something??
The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.
you can try
scanf("%c%*c", &ch1);
where %*c accepts and ignores the newline
one more method
instead of fflush(stdin) which invokes undefined behaviour you can write
while((getchar())!='\n');
don't forget the semicolon after while loop
scanf is a strange function, and there's a classic line from the movie WarGames that's relevant: "The only winning move is not to play".
If you find yourself needing to "flush input", you have already lost. The winning move is not to search desperately for some magic way to flush the nettlesome input: instead, what you need to do is to do input in some different (better) way, that doesn't involve leaving unread input on the input stream, and having it sit there and cause problems, such that you have to try to flush it instead.
There are basically three cases:
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to getchar or fgets. (This is the case you were initially asking about.)
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to scanf("%c").
You are reading numeric input using scanf, and the user is typing non-numeric text, and the non-numeric text is getting left on the input stream, meaning that the next call to scanf fails on it also.
In all three cases, it may seem like the right thing to do is to "flush" the offending input. And you can try, but it's cumbersome at best and impossible at worst. In the end I believe that trying to flush input is the wrong approach, and that there are better ways, depending on which case you were worried about:
In case 1, the better solution is, do not mix calls to scanf with other input functions. Either do all your input with scanf, or do all your input with getchar and/or fgets. To do all your input with scanf, you can replace calls to getchar with scanf("%c") — but see point 2. Theoretically you can replace calls to fgets with scanf("%[^\n]%*c"), although this has all sorts of further problems and I do not recommend it. To do all your input with fgets even though you wanted/needed some of scanf's parsing, you can read lines using fgets and then parse them after the fact using sscanf.
In case 2, the better solution is, never use scanf("%c"). Use scanf(" %c") instead. The magic extra space makes all the difference. (There's a long explanation of what that extra space does and why it helps, but it's beyond the scope of this answer.)
And in case 3, I'm afraid that there simply is no good solution. scanf has many problems, and one of its many problems is that its error handling is terrible. If you want to write a simple program that reads numeric input, and if you can assume that the user will always type proper numeric input when prompted to, then scanf("%d") can be an adequate — barely adequate — input method. But perhaps your goal is to do better. Perhaps you'd like to prompt the user for some numeric input, and check that the user did in fact enter numeric input, and if not, print an error message and ask the user to try again. In that case, I believe that for all intents and purposes you cannot meet this goal based around scanf. You can try, but it's like putting a onesie on a squirming baby: after getting both legs and one arm in, while you're trying to get the second arm in, one leg will have wriggled out. It is just far too much work to try to read and validate possibly-incorrect numeric input using scanf. It is far, far easier to do it some other way.
You will notice a theme running through all three cases I listed: they all began with "You are reading input using scanf...". There's a certain inescapable conclusion here. See this other question: What can I use for input conversion instead of scanf?
Now, I realize I still haven't answered the question you actually asked. When people ask, "How do I do X?", it can be really frustrating when all the answers are, "You shouldn't want to do X." If you really, really want to flush input, then besides the other answers people have given you here, two other good questions full of relevant answers are:
How to properly flush stdin in fgets loop
Using fflush(stdin)
I am surprised nobody mentioned this:
scanf("%*[^\n]");
How can I flush or clear the stdin input buffer in C?
The fflush() reference on the cppreference.com community wiki states (emphasis added):
For input streams (and for update streams on which the last operation was input), the behavior is undefined.
So, do not use fflush() on stdin.
If your goal of "flushing" stdin is to remove all chars sitting in the stdin buffer, then the best way to do it is manually with either getchar() or getc(stdin) (the same thing), or perhaps with read() (using stdin as the first argument) if using POSIX or Linux.
The most-upvoted answers here and here both do this with:
int c;
while ((c = getchar()) != '\n' && c != EOF);
I think a clearer (more-readable) way is to do it like this. My comments, of course, make my approach look much longer than it is:
/// Clear the stdin input stream by reading and discarding all incoming chars up
/// to and including the Enter key's newline ('\n') char. Once we hit the
/// newline char, stop calling `getc()`, as calls to `getc()` beyond that will
/// block again, waiting for more user input.
/// - I copied this function
/// from "eRCaGuy_hello_world/c/read_stdin_getc_until_only_enter_key.c".
void clear_stdin()
{
// keep reading 1 more char as long as the end of the stream, indicated by
// `EOF` (end of file), and the end of the line, indicated by the newline
// char inserted into the stream when you pressed Enter, have NOT been
// reached
while (true)
{
int c = getc(stdin);
if (c == EOF || c == '\n')
{
break;
}
}
}
I use this function in my two files here, for instance. See the context in these files for when clearing stdin might be most-useful:
array_2d_fill_from_user_input_scanf_and_getc.c
read_stdin_getc_until_only_enter_key.c
Note to self: I originally posted this answer here, but have since deleted that answer to leave this one as my only answer instead.
I encounter a problem trying to implement the solution
while ((c = getchar()) != '\n' && c != EOF) { }
I post a little adjustment 'Code B' for anyone who maybe have the same problem.
The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.
Code A
int y;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
continue;
}
printf("\n%c\n", toupper(y));
and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:
Code B
int y, x;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
x = y;
}
printf("\n%c\n", toupper(x));
The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.
If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.
hope it helps someone
Try this:
stdin->_IO_read_ptr = stdin->_IO_read_end;
unsigned char a=0;
if(kbhit()){
a=getch();
while(kbhit())
getch();
}
cout<<hex<<(static_cast<unsigned int:->(a) & 0xFF)<<endl;
-or-
use maybe use _getch_nolock() ..???
Another solution not mentioned yet is to use:
rewind(stdin);
In brief. Putting the line...
while ((c = getchar()) != '\n') ;
...before the line reading the input is the only guaranteed method.
It uses only core C features ("conventional core of C language" as per K&R) which are guaranteed to work with all compilers in all circumstances.
In reality you may choose to add a prompt asking a user to hit ENTER to continue (or, optionally, hit Ctrl-D or any other button to finish or to perform other code):
printf("\nPress ENTER to continue, press CTRL-D when finished\n");
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("\nEnd of program, exiting now...\n");
return 0;
}
...
}
There is still a problem. A user can hit ENTER many times. This can be worked around by adding an input check to your input line:
while ((ch2 = getchar()) < 'a' || ch1 > 'Z') ;
Combination of the above two methods theoretically should be bulletproof.
In all other aspects the answer by #jamesdlin is the most comprehensive.
Quick solution is to add a 2nd scanf so that it forces ch2 to temporarily eat the carriage return. Doesn't do any checking so it assumes the user will play nice. Not exactly clearing the input buffer but it works just fine.
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
scanf("%c", &ch2); // This eats '\n' and allows you to enter your input
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
I have written a function (and tested it too) which gets input from stdin and discards extra input (characters). This function is called get_input_from_stdin_and_discard_extra_characters(char *str, int size) and it reads at max "size - 1" characters and appends a '\0' at the end.
The code is below:
/* read at most size - 1 characters. */
char *get_input_from_stdin_and_discard_extra_characters(char *str, int size)
{
char c = 0;
int num_chars_to_read = size - 1;
int i = 0;
if (!str)
return NULL;
if (num_chars_to_read <= 0)
return NULL;
for (i = 0; i < num_chars_to_read; i++) {
c = getchar();
if ((c == '\n') || (c == EOF)) {
str[i] = 0;
return str;
}
str[i] = c;
} // end of for loop
str[i] = 0;
// discard rest of input
while ((c = getchar()) && (c != '\n') && (c != EOF));
return str;
} // end of get_input_from_stdin_and_discard_extra_characters
Just for completeness, in your case if you actually want to use scanf which there are plenty of reasons not to, I would add a space in front of the format specifier, telling scanf to ignore all whitespace in front of the character:
scanf(" %c", &ch1);
See more details here: https://en.cppreference.com/w/c/io/fscanf#Notes
Short, portable and declared in stdio.h
stdin = freopen(NULL,"r",stdin);
Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:
while ((c = getchar()) != '\n' && c != EOF) { }
A little expensive so don't use it in a program that needs to repeatedly clear the buffer.
Stole from a coworker :)
I'm trying to read a line from stdin but I don't know to properly handle the cases when input size is at least equal to the limit. Example code:
void myfun() {
char buf[5];
char somethingElse;
printf("\nInsert string (max 4 characters): ");
fgets (buf, 5, stdin);
...
printf("\nInsert char: ");
somethingElse = getchar();
}
Now, the user can do three things:
Input less than 4 characters (plus newline): in this case there's nothing left in stdin and the subsequent getchar() correctly waits for user input;
Input exactly 4 characters (plus newline): in this case there's a newline left in stdin and the subsequent getchar() reads it;
Input more than 4 characters (plus newline): in this case there's at least another character left in stdin and the subsequent getchar() reads it, leaving at least a newline in.
Cases 2 and 3 would require emptying stdin using something like while(getchar() != '\n'), whereas case 1 doesn't require any additional action. As I understand from reading answers to similar questions and c-faq, there's no standard/portable way to know whether the actual scenario is the one described in 1 or not.
Did I get it well? Or there actually is a portable way to do it? Or maybe a totally different approach?
The fgets function will store the newline in the buffer if there is room for it. So if the last character in the string is not a newline, you know you need to flush the buffer.
fgets (buf, 5, stdin);
if (strrchr(buf, '\n') == NULL) {
// flush buffer
int c;
while ((c = getchar()) != '\n') && (c != EOF));
}
If ones assumes that a null character '\0' is never read, then #dbush answer will work.
If a null character is read, then strrchr(buf, '\n') does not find any '\n' that may have been read.
Code could pre-set the buffer to see if a '\n' was read in the end.
buf[sizeof buf - 2] = '\n';
if (fgets (buf, sizeof buf, stdin)) {
if (strrchr(buf, '\n') == NULL) {
// incomplete line read. (the usual detection)
} else if (buf[sizeof buf - 2] != '\n') {
// incomplete line read with prior null character (see below note).
}
}
Yet the C standard does not specify that data past what was read in buf[] is unchanged, pre-filling the buffer with some pattern is not sufficient to detect if a null character '\0' was read.
is a portable way to do it?
The most portable way is to use repeated calls to fgetc() or the like instead of fgets().
maybe a totally different approach?
I recommend fgetc() or the common but not C standard getline()
Another alternative: Use scanf("%4[^\n]%n", buf, &n): It is very cumbersome, yet a portable way is possible. It keeps track of the number of characters read before the '\n' even if some are null characters.
int n = 0;
cnt = scanf("%4[^\n]%n", buf, &n); // Cumbersome to get that 4 here.
// Lots of TBD code now needed:
// Handle if cnt != 1 (\n to be read or EOF condition)
// Handle if n == sizeof buf - 1, (0 or more to read)
// Handle if n < sizeof buf - 1, (done, now get \n)
// A \n may still need to be consumed
// Handle EOF conditions
I have a program where the user enters two inputs. Being that I can't control what the user enters, the user can go past the fixed size of the array. Since fgets() appends retains a newline to the end before the null character, in the event that a newline cannot fit when the user goes beyond the intended size, the null character truncates the input. Does the newline character when the user hits enter still exist in the input stream? If so, is this the reason why fgets()skips the second time because of the newline from the first input?
#include <stdio.h>
int main(){
char str[5];
fgets(str,5,stdin);
printf("Output:%s",str);
fgets(str,5,stdin);
printf("Output:%s",str);
return 0;
}
Example Input
ABCDE\n
Output
Output:ABCDOutput:E
After reading this SO answer fgets() isn't prompting user a second time
, the issue seems to be not flushing the input stream via fflush(stdin), but I've heard conflicting information saying as this leads to undefined behavior. My last question is, what would be the appropriate way to clear the input stream if it's the retained newline that's causing issues?
the user can go past the fixed size of the array. Since fgets() appends a newline to the end before the null character
No, it does not. It writes characters read from the input into the provided buffer, up to and including the first newline, or until the specified buffer size is exhausted (less one byte for the string terminator), or until an error occurs or the end of the stream is reached, whichever comes first. The newline is not invented by fgets(); it comes from the input.
, in the event that a newline cannot fit when the user goes beyond the intended size, the null character truncates the input. Does the newline character when the user hits enter still exist in the input stream?
All characters entered by the user and not copied into the buffer remain waiting to be read in the stream. That will include the newline, if the user entered one.
If so, is this the reason why fgets()skips the second time because of the newline from the first input?
fgets() does not skip, but it does pick up where the previous call left off transferring characters from input to the buffer. No characters are lost. That means that the second call returns part of the first input line if the first call did not return the whole thing. You need to account one way or another for the possibility that the input does not conform to your line-length expectations.
the issue seems to be not flushing the input stream via fflush(stdin),
No, it isn't. Flushing is for sending buffered output to the underlying output device. Flushing an input stream produces undefined behavior. In principle, that could manifest as a buffer dump, and a given implementation might even specify such behavior, but you don't want that because there may be more data buffered than you want to get rid of.
but I've heard conflicting information saying as this leads to undefined behavior. My last question is, what would be the appropriate way to clear the input stream if it's the retained newline that's causing issues?
You read from the input until you've read the newline. There are plenty of I/O functions to choose from to accomplish this. fgets() itself might prove convenient, since you're already using it:
char str[5];
if (fgets(str, 5, stdin)) {
printf("Output:%s", str);
// read and consume the tail of the line, if any (overwrites str)
while (!strchr(str, '\n') && fgets(str, 5, stdin)) { /* empty */ }
}
fgets() reads until
1) New-line
2) Buffer is full
3) End-of-file
4) Input error (rare)
This code reads and takes care of #3 & #4
#define N 5
char buf[N];
if (fgets(buf, sizeof buf, stdin) == NULL) {
// Handle EOF or Error
return EOF;
}
To distinguish if a '\n' is present ... (#2 from #1)
// look for a lack of \n
if (strchr(buf, '\n') == NULL) {
And if so, read until it is found or EOF.
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF);
}
--
Do not use the following code. It can be exploited by reading a null character as the first character.
size_t len = strlen(buf);
if (buf[len - 1] != '\n') { // bad way to detect \n
Could use
if (len > 0 && buf[len - 1] != '\n') { // Good
Being that I can't control what the user enters...
No, you cannot.
the user can go past the fixed size of the array.
Right. This is always a concern. However, In general you'll want to arrange things so that this rarely happens.
For example, if you really want to limit the user to (say) a 4-character-long input string, let him type whatever he wants, then see how much he typed, and if it was more than your limit, print a nice error message or something. But I do not recommend calling fgets(str, 5, stdin) if you're expecting 4 characters of input plus a newline, because it's just way too hard to recover when (not if) the user types too much.
in the event that a newline cannot fit when the user goes beyond the intended size, the null character truncates the input. Does the newline character when the user hits enter still exist in the input stream?
Absolutely yes.
If so, is this the reason why fgets()skips the second time because of the newline from the first input?
Pretty much yes.
I recommend allocating a much bigger buffer, and then proceeding something like this:
char inpbuf[512);
if(fgets(inpbuf, sizeof(inpbuf), stdin) == NULL) {
fprintf(stderr, "end of file\n");
return;
}
char *p = strrchr(inpbuf, '\n');
if(p == NULL) {
fprintf(stderr, "looks like you typed *way* too much\n");
return;
}
*p = '\0'; /* erase the \n */
if(strlen(inpbuf) > 4) {
fprintf(stderr, "you typed too much (max 4)\n");
return;
}
strcpy(str, inpbuf);
printf("Output:%s", str);
One glitch with this code as written, though: if the user hits the end-of-file key (control-D on Unix/Linux) before hitting Return, you'll falsely get the "looks like you typed way too much" message.
If the string read by fgets doesn't end in a newline, you know it's still in the buffer. In that case, call getchar in a loop until you get a newline.
fgets(str,5,stdin);
printf("Output:%s",str);
if (strchr(str, '\n') == NULL) {
int c;
while ((c = getchar()) != EOF && c != '\n');
}
fgets(str,5,stdin);
printf("Output:%s",str);
I was always bad at inputting characters in C and this is another example. Though I understood (maybe) what's happening but I can't figure out the solution.
I have the following code
scanf("%ld %ld",&n,&m);
for(i=0;i<n;i++)
scanf("%ld",&array[i]);
for(i=0;i<m;i++)
{
fflush(stdin);
//inputting a character 'R' but it is picking '\n' from past buffer
scanf("%c",&query);
//As a result of above problem, it is also acting wierd for same reason
scanf("%ld",&d);
printf("%c %ld",query,d);
printf("\nI=%ld\n",i);
}
Please help me figure out the reason why its happening and what is the solution.
Using scanf with %d (or %ld) only extracts the number from the input stream; it leaves the newline in the stream.
So when you write scanf("%c", it reads that newline.
To fix this (if your intent is that scanf("%c" reads the first character of the next line), you need to flush the input of the previous line. One way to do that is:
int ch; while ( (ch == getchar()) != EOF && ch != '\n' ) { }
Your line fflush(stdin); causes undefined behaviour - don't do that. The fflush function is only for output streams.
Also , it is a really good idea to check the return value of scanf. If it was not what you expected then you may wish to take some action, instead of pretending that a number was entered.
Since you are tired of input issues, I can give you a method that can help to simplify your live.
I can observe that:
You have problems in handling end-of-lines.
Sometimes you need to input numbers and sometimes you need characters or another kind of input. So, you (think that you) are forced to use formatted input.
My advice is that you separate the issue of reading input from the issue of interpreting data entered from input.
The standard C brings only a few functions to handle input/output operations, in the standard header <stdio.h>.
If you are not interested in very sofisticated I/O results, the standard library is enough.
However, the functions of <stdio.h> usually have the effect that input is read one line at the time, which includes the end-of-line character: '\n'.
What you can do, then, it's what follows:
Read a line with fgets(..., stdin) and put the result in a buffer (not so long), used only for this purpose.
Once you have read an entire line, no more issues with end-of-line will bother you.
Then, re-read this line, that it's held in a buffer, and apply to it all the formatted input that you need.
A short example:
#include <stdio.h>
int main(void) {
char buffer[200] = ""; // Initialize array to 0's
long int n, m;
char c;
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer,"%ld %ld",&n,&m);
// Now you have processed the "integer number" input,
// read input characters again, withou any "flushes" and extrange things:
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer,"%c", &c);
fgets(buffer, sizeof(buffer), stdin);
// and so on...
}
Thus, every time you need to separate a section of input from a previous one, just do a new line reading with fgets(..., stdin), which stores the input in buffer, and then process the buffer with sscanf(), which applies the format string to the buffer instead of the input itself (in its flesh).
Note: This method can have a little problem: If the string input has more than sizeof(buffer) characters (in the example: 200), the line is not completely read. This situation can be handled by checking if the character before last in buffer is not equal to '\n' nor '\0'. In such a case, you would make automatically some kind of "flushing input" operation (reading and discarding characters till the next end-of-line is found).