C,读取多个数字从单一的输入线(scanf函数?) [英] C, reading multiple numbers from single input line (scanf?)

查看:259
本文介绍了C,读取多个数字从单一的输入线(scanf函数?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用C语言编写的应用程序,它预计在输入两行。
首先输入讲述一个int数组有多大将和第二个输入包含空格隔开的值。
例如,下面的输入

  5
1 2 3 4 99

应该创建包含数组 {1,2,3,4,99}

什么是这样做的最快方法?我的问题是不通过整个字符串循环检查,如果它是空格或数字读取多个号码?

感谢。


解决方案

  INT I,大小;
INT * V;
scanf函数(%d个,&安培;大小);
V =的malloc(大小*的sizeof(INT));
对于(i = 0; I<大小;我++)
    scanf函数(%d个,&安培; v [I]);

记住免费(V)你做了!

另外,如果由于某种原因,你已经拥有了数字字符串中,你可以使用的sscanf()

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.

解决方案

int i, size;
int *v;
scanf("%d", &size);
v = malloc(size * sizeof(int));
for(i=0; i < size; i++)
    scanf("%d", &v[i]);

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

这篇关于C,读取多个数字从单一的输入线(scanf函数?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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