[英]Inputting array in C
基本上我有一个C程序,用户在其中输入数字(例如4)。 定义的是将进入数组的整数数量(最大为10)。 但是我希望用户能够将它们输入为“ 1 5 2 6”(例如)。 即作为空格分隔的列表。
至今:
#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语句后不应使用分号。 编译器应该给您警告,如果不是错误的话。
#include <stdio.h>
int main(int argc,char *argv[])
{
int no,noArray[10];
int i = 0;
scanf("%d",&no);
while(no > 10)
{
printf("The no must be smaller than 10,please input again\n");
scanf("%d",&no);
}
for(i = 0;i < no;i++)
{
scanf("%d",&noArray[i]);
}
return 0;
}
您可以这样尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.