基本上我有一个 C 程序,用户在其中输入一个数字(例如 4)。它定义的是要进入数组的整数数量(最多 10 个)。不过,我希望用户能够将它们输入为“1 5 2 6”(例如)。 IE。作为空格分隔的列表。
到目前为止:
#include<stdio.h>;
int main()
{
int no, *noArray[10];
printf("Enter no. of variables for array");
scanf("%d", &no);
printf("Enter the %d values of the array", no);
//this is where I want the scanf to be generated automatically. eg:
scanf("%d %d %d %d", noArray[0], noArray[1], noArray[2], noArray[3]);
return 0;
}
不确定我该如何做到这一点?
谢谢
最佳答案
scanf自动消耗格式说明符/百分号之前的所有空格(%c 除外,它一次消耗一个字符,包括空格)。这意味着像这样的行:
scanf("%d", &no);
实际上读取并忽略要读取的整数之前的所有空格。因此,您可以使用 for 循环轻松读取由空格分隔的任意数量的整数:
for(int i = 0; i < no; i++) {
scanf("%d", &noArray[i]);
}
请注意,noArray 应该是一个整数数组,并且您需要将每个元素的地址传递给 scanf,如上所述。另外,#include 语句后不应有分号。如果没有错误的话,编译器应该给你一个警告。
关于c - 在C中输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13371648/