C语言中如何读取带空格的字符串?
scanf("%s",str) 不会这样做。它将在第一个空格处停止读取。 当字符串很大时,gets(str) 也不起作用。有什么想法吗?
scanf("%s",str) won't do it. It will stop reading at the first space.
gets(str) doesn't work either when the string is large. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 fgets 和 STDIN 作为文件流。然后您可以指定要读取的数据量以及将其放置在何处。
use fgets with STDIN as the file stream. Then you can specify the amount of data you want to read and where to put it.
试试这个
或这个
Try this
or this
创建您自己的函数来读取一行。以下是您基本上必须做的事情:
实现可能有点棘手:-)
您需要考虑需要传递给函数的内容(至少是数组的地址及其大小);以及当一切“正常”或出现错误时函数返回什么。您需要确定什么是错误(一个 10Gbytes 长且没有 '\n' 的字符串是错误吗?)。您需要决定如何增长阵列。
编辑
实际上,
fgetc
可能比fgets
更好Create your own function to read a line. Here's what you basically have to do:
The implementation may be a bit tricky :-)
You need to think about what you need to pass to your function (at the very least the address of the array and its size); and what the function returns when everything "works" or when there is an error. You need to decide what is an error (is a string 10Gbytes long with no '\n' an error?). You need to decide on how to grow the array.
Edit
Actually it may be better to
fgetc
rather thanfgets
你什么时候想停止阅读?在 EOF 处,在特定字符处,还是什么?
您可以使用 %c 读取特定数量的字符
您可以使用 %[ 读取特定字符(或最多排除的字符)
When do you want to stop reading? At EOF, at a specific character, or what?
You can read a specific number of characters with %c
You can read specific characters (or up to excluded ones) with %[
要读取带有空格的字符串,可以执行以下操作:
To read string with space you can do as follows: