I have gone through many questions and blogs and books, but I guess I'm just not able to relate things properly. What does scanf do after scanning? It reads everything except space, tab and newline, but what does it do to newline?? I'm unable to remove newline any way after scanning input. For example, consider this as input:-
5
Abcdefgh
Now, I have scanned 5 as integer,
scanf("%d", &i);
but how do I remove '\n' in order to read everything ahead one character at a time? I want to use:-
while((c=getchar())!='\n'){//Do something}
The '\n' is supposed to be the one AFTER the string, but getchar() gets the one after 5 and loop terminates before even running once. I guess I'm just missing a very little trick.
scanf("%d", &i);
while((c=getchar())!='\n'){
//Do something with the character
}
Input File:-
5
ABCDEF
Expecting while loop to run, while it doesn't run. Because it catches '\n' after 5. I have tried adding getchar() in between scanf() and while(), but then program stucks and does nothing.
If you add a space after the
%d
in yourscanf
format specifier,scanf
will not return until it encounters any non-whitespace character. This will effectively consume any number of newlines or other spaces in your input. As pointed out by @BlueMoon, note that this relies on the program receiving more non-whitespace input after the newline. So it works for this example but might cause trouble elsewhere.Here's a minimal example:
sample input:
output:
edit: Note that this issue can be circumvented by using
fgets
to read a line into a character buffer, then extracting the integer usingsscanf
:fgets
reads until a newline or end of file is encountered, orSIZE-1
bytes have been read. Assuming you're only expecting the line to contain one integer, this limitation shouldn't be an issue. As long asSIZE
is large enough, the newline will be consumed byfgets
and the subsequentgetchar
in the loop will work as expected.Since you are using Windows, there is a
'\r'
character before the'\n'
character.The "adding a
getchar();
before yourwhile
loop" trick doesn't work because thisgetchar()
is getting the'\r'
character. So when thewhile
condition is first evaluated,c
is'\n'
.So a trivial fix would be to use TWO
getchar()
calls to consume the'\r\n'
. However, this is not very portable, that is, it won't work on other systems.So I would use the following:
You can use a
getchar()
right after thescanf()
call to consume the\n
so that it doesn't interfere with your loop.I ran the above code in the same as you do:
./a.out < file
on Linux and on windows usingmingw
and I don't see any problem.If you take character or string inputs, use
getchar()
after every integer inputs. This will remove the\n
from the input buffer.