Recommend posting more of your coding goal so we may suggest how to avoid the need to “not skip \n”.
scanf()
does not skip '\n'
. Select format specifies like "%d"
direct scanf()
to skip leading white-pace – including '\n'
.
If one wants to use scanf()
and not skip '\n'
, use format specifiers like "%[]"
or "%c"
. Alternatively, try a new approach with fgets()
or fgetc()
.
If code must use scanf()
and not skip leading '\n'
when scanning an int
, suggest the following:
char buf[100];
int cnt = scanf("%99[-+0123456789 ]", buf);
if (cnt != 1) Handle_UnexpectedInput(cnt);
// scanf the buffer using sscanf() or strtol()
int number;
char sentinel
cnt = sscanf(buf, "%d%c", &number, &sentinel);
if (cnt != 1) Handle_UnexpectedInput(cnt);
Alternative: consume all leading whitespace first, looking for \n
.
int ch;
while ((ch = fgetc(stdin)) != '\n' && isspace(ch));
ungetc(ch, stdin);
if (ch == '\n') Handle_EOLchar();
int number;
int cnt = scanf("%d", &number);
if (cnt != 1) Handle_FormatError(cnt);