用户输入并插入数组
我是 C 新手。我需要知道如何请求用户输入(可以是任意数量的单词),然后将字符放入数组中。
我知道这不应该太难回答,但谷歌只是让我感到困惑。
提前致谢
I'm new to C. I need to know how to ask for the user input, which could be an arbitrary number of words, and then put the characters into an array.
I know this shouldn't be too hard to answer, but Google is just confusing me.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解你的问题,你需要的是读取一些未知大小的用户输入,从而将这些信息存储到一个 char 数组中,对吗?如果是这种情况,一种可能的解决方案是使用一个 char 数组,将其分配给默认的固定大小,这会动态地动态重新分配其大小。
一旦循环输入的字符,同时验证没有到达 EOF,您应该将字符附加到数组中。然后,技巧是检查数组是否足够大以容纳用户输入的字符。如果没有,则必须重新分配数组的大小。
解决方案的示例实现可能看起来有点像这样:
性能方面,我不确定这可能是最好的解决方案,但我希望这可以帮助您解决问题。
亲切的问候
〜E。
If I understand your problem correctly, what you need is to read user input of some unknown size, thus store this information into a char array, right? If this is the case, one possible solution would be to have an char array with which should be allocated to a default fixed size, this dynamically reallocate it's size on the fly.
Once looping over the characters of the input, while verifying that you haven't hit an EOF, you should append the char to the array. The trick is then to check whether the array is large enough to hold the characters from the user's input. If not, you have to reallocate the array's size.
A sample implementation of a solution could look somewhat like this:
Performance wise, I am not all to sure this may be the best solution, but I hope this may aid you on solving your problem.
Kind regards
~ E.
开始更加努力的学习...
一个小帮助:
printf()
scanf()
或fgets()
(第二个更好,但有点更难...)Start studying harder...
A small help:
printf()
scanf()
orfgets()
(the second is better but a little harder...)