C,从单个输入行读取多个数字(scanf?)
我用 C 编写了一个应用程序,需要输入两行。 第一个输入告诉 int 数组有多大,第二个输入包含由空格分隔的值。 例如,以下输入
5
1 2 3 4 99
应创建一个包含 {1,2,3,4,99}
的数组,
最快的方法是什么?我的问题是读取多个数字而不循环遍历整个字符串检查它是空格还是数字?
谢谢。
I have written an app in C which expects two lines at input.
First input tells how big an array of int will be and the second input contains values separated by space.
For example, the following input
5
1 2 3 4 99
should create an array containing {1,2,3,4,99}
What is the fastest way to do so? My problem is to read multiple numbers without looping through the whole string checking if it's space or a number?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
完成后记得
free(v)
!另外,如果由于某种原因您已经在字符串中包含了数字,则可以使用 sscanf()
Remember to
free(v)
after you are done!Also, if for some reason you already have the numbers in a string, you can use
sscanf()
这里“N”是数组“A”的数组元素数
Here 'N' is the number of array elements of Array 'A'
这是取自 http://www.cplusplus.com/reference/cstring/strtok/ 的示例 我已经适应了我们的环境。
它将 str 链拆分为子链,然后将每个部分转换为 int。我希望输入行是用逗号分隔的数字,没有其他内容。大小是数组的大小。你应该这样做 scanf("%d", &size);正如德尼尔森在回答中所说。最后,您将获得包含所有值的 int 数组。
Here is an example taken from http://www.cplusplus.com/reference/cstring/strtok/ that I've adapted to our context.
It splits the str chain in sub chains and then I convert each part into an int. I expect that the entry line is numbers seperated by commas, nothing else. Size is the size of your array. You should do scanf("%d", &size); as Denilson stated in his answer. At the end, you have your int array with all values.
scanf()
有点让人头疼。看看strtol()
来解决这类问题,它会让你的生活变得非常轻松。scanf()
is kind of a pain in the neck. Check outstrtol()
for this kind of problem, it will make your life very easy.这段代码采用直接的方法,通过 getchar() 读取每个字符。我们继续读取一个数字,直到找到一个空格。之后数组的索引“i”就会更新。这会重复直到 newline('\遇到 n')
This code employs a straight forward approach of reading each character through getchar().We go onto reading a number util we find a blank space.The index 'i' of the array gets updated after that.This is repeated until newline('\n') is encountered