I’m doing homework that asks me to read an integer n representing the size of a loop and then read a line of characters n times and print it right after the user’s input. So I used scanf and then I print it with printf. The problem is that if the user’s input is only a newline character, it should print another \n, but scanf seems to ignore the input when it’s a single \n.
Is there any way to make this assignment with scanf or should I try something else?
int i;
scanf("%d", &i);
for(int ct=0; ct<i; ct++)
{
char buff[28];
scanf("%s", buff); // if I just press enter here
prtinf("%s\n", buff); // then I must get \n\n here
}
Using
fgetsto read in a line is simpler and more robust:It doesn’t work with
scanf("%s",buff)because mostscanfconversions ignore leading white space:So if the user inputs an empty line,
scanfignores that input unless its format is one of the exceptional.You can use
scanfwith a character set format instead,to read all characters until a newline (but limited to
28 - 1here to avoid buffer overruns), and then consume a newline without storing it (the*in the%*cconversion specifier suppresses assignment), that would handle non-empty lines consisting entirely of whitespace, which the%sconversion would not. But if the first character of the input is a newline, the%27[^\n]conversion fails (thanks to chux for drawing attention to that), the newline is left in the input buffer, and subsequent scans with that format would also fail if the newline isn’t removed from the input buffer.A somewhat robust (but ugly; and not dealing with too long input) loop using
scanfwould, as far as I can see, need to check for a newline before scanning, e.g.Use
fgets, really. It’s better.