c - Why does the presence of `n` in the input sentence before `\n` give wrong output? -
i want input sentence (containing possible characters) , print it. there catch. if there \n
in sentence part of sentence before \n
should printed out (i.e. \n
should signify end of inputted sentence). wrote code situation :
#include <stdio.h> main() { char ch[100]; printf("enter sentence"); scanf("%99[^\\n]",&ch); printf("%s",ch); }
this code seems work fine fails in situation. if there character n
anywhere in sentence before \n
prints first word of sentence! why happen? how can fix bug?
but in case fails:
detail comments:
q: want to stop @ newline, or @ backslash followed n?
a: slash followed n
the []
conversion specifier of scanf()
works defining accepted (or, ^
, rejected) set of characters. %[^\\n]
stop scanning @ first \
or first n
-> can't solve problem scanf()
.
you should read line of input fgets()
, search occurence of "\\n"
strstr()
.
side note: there's error in program:
char ch[100]; scanf("%99[^\\n]",&ch);
ch
evaluates pointer first element of array (so, fine parameter scanf()
), while &ch
evaluates pointer array, not scanf()
expects.
(the difference in type, address same)
Comments
Post a Comment