I'm using freopen function to read files. But when i use scanf statement to scan integers, it skips '\n' character. How can i avoid skipping '\n' by scanf.
-
2By default, scanf for an integer will skip all whitespace characters ('\n' being one of them) until the next integer. If you want to read until end-of-line, consider using gets/fgets instead of scanf. – Gassa Mar 11 '14 at 14:47
-
2What do you mean by "skips '\n'"? It's better to show some code for detail. – feihu Mar 11 '14 at 14:55
3 Answers
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);

- 143,097
- 13
- 135
- 256
You can't! But don't worry, there are workarounds.
Workaround:
Read input one line at a time (using fgets) and then use sscanf
to scan for integers.
#define LINE_MAX 1000
line[LINE_MAX];
int num;
while (fgets(line, LINE_MAX, fp) != NULL) {
if (sscanf(line, "%d", &num) == 1) {
// Integer scanned successfully
}
}

- 33,105
- 5
- 57
- 82
xscanf
functions will process the strings by DFA. It will search the format which is given by fmt argument, each space chars(space,\t,\n,\r etc.) will be skipped. You can insert these space chars to fmt for matching.
For example, how it does skipping:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
char* s = "1 2 \n 3 4 \n 5 \n \n \n 6";
int i,c;
int tot=0;
while(sscanf(s+tot,"%d%n",&i,&c)){
printf("'%s':%d,cnt=%d\n",s+tot,i,c);
tot += c;
}
return 0;
}
/*** Output:
'1 2
3 4
5
6':1,cnt=1
' 2
3 4
5
6':2,cnt=2
'
3 4
5
6':3,cnt=4
' 4
5
6':4,cnt=2
'
5
6':5,cnt=4
'
6':6,cnt=8
'':6,cnt=8
***/

- 907
- 8
- 10