I knew this for two years now, but it dint strike me before to put it up in the blog; don’t know why ?
Its easy and simple, I don’t think I need to explain. Only the syntax needs to be remembered.
scanf(” %[^\n]s”,a);
May be you get a question in your mind. What does ‘[^\n]‘ do ? Does it set the delimiter to ‘\n’. Well, you on the right track. Yes, it does. Instead on ‘\n’, if you had put a ‘\t’ it would consider all words with spaces as string until you press a ‘Tab’. You can even have a ‘ ‘(a space). The scanf can be expanded as
scanf(” %[^ ]s”,a); // Note – There is a space after ^
The only differece between scanf(” %s”,a) and scanf(” %[^ ]s”,a) is that, when you enter a string with two words, the former considers each word as a new string whereas the latter consider only the first word as a string and the other word is ignored.
As a Example, consider the string “Hello World“, the former reads “Hello” and “World” as two strings (if you had called ‘scanf’ twice) and the latter reads only the first word “Hello” (even if you had called ‘scanf’ twice) ! Go ahead and experiment with other delimiters !! ![]()


Wow boss thanks.
It is so interesting.
Thank You
thnx.. but what u wrote in last two paragraphs is not working. In both the cases scanf(“%s”, str); & scanf(“%[^ ]s”, str); it is taking the two words as two strings.
Use either %[] or %s, but not %[]s
The reason that in the example of the author only the first word is matched, is that the ‘s’ after the specifier (which is %[^ ]) is never matched! Furthermore, %s is the same as %[^ \t\r\n]
You are right! The author’s misleading something. One shound not add ‘s’ after %[].
This is fantastic ! You saved my day ! Thanks a lot !
Thanks dude, you kinda saved ma day. It worked like a charm. Keep up the good work!
Great, it is explained in the standard for C99, but the explanation there is quite obtrusive…
Apparently, you also could use the characters you allow in the string just removing the ^, and you can use – for an interval of letters, for instance:
char str[256];
scanf(” %[ A-Z]255s”, str);
will read an string that includes only blank spaces and capital letters up to 255 chars.
Thanks a lot man! Not exactly what I was looking for, but it solved my problem nicely.
Thankyou.. it is very helpful