How to Take whitespace in Input in C

2019-04-06 18:29发布

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);

7条回答
We Are One
2楼-- · 2019-04-06 19:02

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.

查看更多
登录 后发表回答