[英]how to create an array from one line of console input in C?
I want to create a two dimensional array where number of rows and columns are fixed and column values will be taken from console input. 我想创建一个二维数组,其中行数和列数是固定的,并且列值将从控制台输入中获取。
void main() {
int myArray[3][5];
int i;
int a, b, c, d, e; // for taking column values
for (i = 0; i < 3; i++) { // i represents number of rows in myArray
printf("Enter five integer values: ");
// taking 5 integer values from console input
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);
// putting values in myArray
myArray[i][1] = a;
myArray[i][2] = b;
myArray[i][3] = c;
myArray[i][4] = d;
myArray[i][5] = e;
}
// print array myArray values (this doesn't show the correct output)
for (i = 0; i < 3; i++) {
printf("%d\t %d\t %d\t %d\t %d\t", &myArray[i][1], &myArray[i][2],
&myArray[i][3], &myArray[i][4], &myArray[i][5]);
printf("\n");
}
}
when I run this program, it takes input correctly, but doesn't show the array output as expected. 当我运行该程序时,它正确地接受了输入,但未按预期显示数组输出。 How could I do this, any idea?
任何想法,我该怎么办? please help.
请帮忙。
Your second dimension is declared from myArray[i][0] to myArray[i][4]. 您的第二个维度是从myArray [i] [0]声明为myArray [i] [4]。 Its not from myArray[i][1] to myArray[i][5]
它不是从myArray [i] [1]到myArray [i] [5]
You had unnecessary & operators in final print. 您在最终印刷中有不必要的&运算符。 I also removed your a, b, c, d, e variables in order to make the code more concise.
我还删除了您的a,b,c,d,e变量,以使代码更简洁。 You can scanf the values in the arrays directly passing the address of each element.
您可以扫描数组中的值,直接传递每个元素的地址。
#include <stdio.h>
void main()
{
int myArray[3][5];
int i;
for(i=0; i<3; i++){ //i represents number of rows in myArray
printf("Enter five integer values: ");
//taking 5 integer values from console input
scanf("%d %d %d %d %d",&myArray[i][0], &myArray[i][1], &myArray[i][2], &myArray[i][3], &myArray[i][4]); // you can directly scan values in your matrix
}
for(i=0; i<3; i++){
printf("%d\t %d\t %d\t %d\t %d\t\n", myArray[i][0], myArray[i][1], myArray[i][2], myArray[i][3], myArray[i][4]); // no need for the & sign which returns the address of the variable
}
}
Try using %1d
尝试使用
%1d
#include <stdio.h>
int main(void)
{
int i;
int x[5];
printf("Enter The Numbers: ");
for(i = 0; i < 5; i++)
{
scanf("%1d", &x[i]);
}
for(i = 0; i < 5; i++)
{
printf("%d\n", x[i]);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.