Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c99 - C, reading multiple numbers from single input line (scanf?)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...