处理 C 中的字符串输入
如果在使用之前需要声明一个 char 数组,那么如何声明它才能用于存储输入?
例如,用户输入一个句子或一系列单词。如何存储它以便可以对其进行操作?
除了声明一个足够大以处理预期输入的数组之外,正确的方法是什么?
If a char array needs to be declared before it is used, how does one declare one so that is can be used to store input?
e.g. The user enters a sentence or series of words. How is this stored so that it can be manipulated?
What is the correct way rather than just declaring an array which is large enough to handle expected input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您正在谈论控制台输入,您别无选择,只能拥有固定大小的缓冲区并使用不允许超过
FIXED_SIZE
的安全功能存储在您的缓冲区中。一个例子是:
您必须警告您的用户,任何超过 1023 个的字符都将被忽略。
如果您想访问用户输入的最后一个字符:
If you are talking about console input, you have no choice but to have a FIXED SIZE buffer and use a secure function not allowing more than
FIXED_SIZE
to be stored on your buffer.An example would be:
You must warn your user that any characters beyond 1023th will be ignored.
If you want to access last character the user entered:
我通常使用以下函数:
它使用缓冲区溢出安全
fgets
和一些支持代码来确定您输入的行是否太长。当然,您可以读取部分行并执行内存重新分配来存储任意大小的输入字符串,但通常只需设置足够大的上限并允许这样做(例如 1K)就足够了。如果有人输入的姓名或地址超出了这个范围,他们可能只是在愚蠢:-)
我之前实际上已经使用过这个技巧(部分读取和重新分配)来进行用户输入,但说实话,需要它非常罕见,以至于它没有进入我的“重要源代码片段”存储库。
使用
fgets
可以防止缓冲区溢出的可能性,这对用户输入来说是一个大危险。如果您想测试该代码,请尝试添加:
并运行一些示例:(
第二个示例输入 CTRLD,文件立即结束)。
I usually use the following function:
It uses the buffer-overflow-safe
fgets
with some supporting code to figure out if the line you entered was too long.You can of course, read partial lines and perform memory re-allocations to store an arbitrary sized input string but usually it's more than adequate to just set a large enough upper boundary and allow for that (say 1K for example). If anyone enters more than that for their name or address, they're probably just being silly :-)
I've actually used that trick (partial reads and reallocs) to do user input before but, to be honest, the need for it was so rare that it didn't make it into my "important source code snippets" repository.
The use of
fgets
prevents the possibility of buffer overflow which is the big danger to user input.If you want to test that code, try adding:
and some sample runs:
(that second one was entering CTRLD, an immediate end of file).
通过缓冲区输入 ? (用户将其文本写入一定大小的缓冲区,当缓冲区已满时,程序使用 realloc 更改目标数组的大小)
(您需要使用 char* 而不是 char[] )
Input via buffer ? ( User writes its text to buffer of some size, when buffer is full, programm changes size of target array using realloc )
( you need to use char* instead of char[] )