Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Take whitespace in Input in C

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);
like image 510
itsaboutcode Avatar asked Oct 12 '09 17:10

itsaboutcode


People also ask

How does C handle whitespace?

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.

How do you give spaces in C?

For just a space, use ' ' .

Does scanf read spaces?

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.

Does scanf skip whitespace?

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.


1 Answers

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.

like image 146
Carl Norum Avatar answered Sep 24 '22 03:09

Carl Norum