如何采取空白的输入用C [英] How to Take whitespace in Input in C

查看:144
本文介绍了如何采取空白的输入用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想采取字符数组从控制台,它包括空格,我知道C中的唯一方法是scanf函数,但它错过停止服用输入一旦击中空白。我该怎么办?

下面是我在做什么。

 字符地址[100];scanf函数(%S,地址);


解决方案

尝试使用与fgets()。它会读取你选择的流的完整产品线(标准输入,我猜你正在寻找)。对于你的情况的一个例子:

 字符地址[100];与fgets(地址,100,标准输入);

与fgets()将至多读取第二个参数(负一)传递的字符数。没有缓冲区溢出,你会得到整个排队并包括一个换行符(或最多EOF)。注意,因为要读取的字符的最大数目是参数之一,它是可能的,你会得到一个局部线。检查是否返回的字符串中的最后一个字符的'\\ n',你就会知道你有一个完整产品线。 EOF检测是pretty过于简单;一个 NULL 返回值和检查错误号应该帮助你。

感谢Chris(下同),关于部分行的地步。

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

解决方案

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.

这篇关于如何采取空白的输入用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆