I wanted to take character array from console and it also include white spaces, the only method i know in C is scanf, but it miss stop taking input once it hit with white space. What i should do?
Here is what i am doing.
char address[100];
scanf("%s", address);
See
fgets()
Further detail available in many SO questions, for example input-string-through-scanf.
(Due to popular demand, refrence to
gets()
was removed)Personally I would use fgets, but that has been already pointed out here. One way of doiung it using scanf would be
This takes in all chars until a '\n' is found.
You can try something like this:
There are ways to do it with
scanf()
, but in my humble opinion they get ugly fast. The common pattern (that surprisingly hasn't been mentioned yet) is to read the string in withfgets()
and then usesscanf()
to process it.sscanf()
works likescanf()
, only instead of processing the standard input stream, it processes a string that you pass to it (the same wayprintf()
andsprintf()
are related). The basics:If you want to take input until new line using a dynamic array inside struct, this may be useful:
My style.