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);
When parsing code, the C compiler ignores white-space characters unless you use them as separators or as components of character constants or string literals. Use white-space characters to make a program more readable. Note that the compiler also treats comments as white space.
For just a space, use ' ' .
Effect of adding whitespace in the scanf() function in CAdding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed.
This happens because scanf skips over white space when it reads numeric data such as the integers we are requesting here. White space characters are those characters that affect the spacing and format of characters on the screen, without printing anything visible.
Try using fgets(). It will read a complete line from a stream of your choice (stdin, I guess you're looking for). An example for your case:
char address[100];
fgets(address, 100, stdin);
fgets() will read at most the number of characters passed in the second argument (minus one). No buffer overflow, and you'll get the whole line up to and including a newline character (or up to EOF). Note that since a maximum number of characters to read is one of the parameters, it is possible that you will get a partial line. Check to see if the last character in the returned string is '\n', and you'll know you got a complete line. EOF detection is pretty straightforward too; a NULL
return value and a check to errno
should help you out.
Thanks to Chris (below), for the point about partial lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With