2014-04-07 40 views
1

在C中,我可以使用scanf读说3个整数用空格从标准输入这样的分离:如何扫描一行n个整数?

#include <stdio.h> 

int main() { 
    int a, b, c; 
    scanf("%d %d %d", &a, &b, &c); 
} 

,如果我不知道有多少整数是前手排在哪?假定用户提供整数数量:

#include <stdio.h> 

int main() { 
    int howManyIntegersToRead; 
    scanf("%d", &howManyIntegersToRead); 
    // Read in the integers with scanf(...); 
} 

我需要的malloc大小sizeof(int) * howManyIntegersToRead字节数组。我如何实际将标准输入数据读入分配的内存?我无法构建一个带有howManyIntegersToRead%ds的格式化字符串。那么,我可以,但是有一个更好的方法。

回答

5

您可以尝试像这样使用for循环:

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

不占多行输入。 –

+1

是的,'%d'跳过空格(包括换行符) –

1

使用动态分配和循环。

#include <stdio.h> 
#include <malloc.h> 

int main() 
{ 
    int count, i; 
    int *ar; 

    printf("Input count of integers: "); 
    scanf("%d", &count); 

    ar = malloc(count * sizeof(int)); 
    if (ar == NULL) 
    { 
     fprintf(stderr, "memory allocation failed.\n"); 
     return -1; 
    } 

    for (i = 0; i < count; i++) 
    { 
     scanf("%d", &ar[i]); 
    } 
} 
2
#include <stdio.h> 

int main() { 
    int howManyIntegersToRead; 
    scanf("%d", &howManyIntegersToRead); 
    // Read in the integers with scanf(...); 
    // allocate memory 
    int a[howManyIntegersToRead]; 

    for(int i=0;i<howManyIntegersToRead;i++) 
     scanf("%d",&a[i]); 
} 
+1

没有VLA(特别是VC++,它不在C99中),这将不起作用。 – ikh

+0

@ikh什么是VLA? –

+1

[Variables Length Array](http://en.wikipedia.org/wiki/Variable-length_array):'int a [howManyIntegersToRead]'。在C++和C99之前,它都不是标准的。 – ikh

1
#include <stdio.h> 
#include <stdlib.h> 

int main(void) { 

    int* integers, i = 0; 
    do { 

    integers = realloc(integers, sizeof(int) * (i + 1)); 
    if(integers == NULL){ 
     return -1; 
    } 
    printf("enter an integer: "); 
    scanf(" %d", &integers[i]); 
    printf("\nentered: %d\n", integers[i]); 
} while(integers[i++] != 0);//here put your ending of choice 


free(integers); 
return 0; 
}