在数组中输入时循环无法正常工作

问题描述 投票:0回答:2

scanf
的循环不适用于索引(即 2)。在
printf
循环中,我得到两个索引的垃圾输出。我不知道这里发生了什么。

#include <stdio.h>
int main() {
    int i;
    char name[3];
    float price[3];
    int pages[3];

    printf("Enter names, prices and pages of 3 books:\n ");
    for (i = 0; i <=2; i++) {
        scanf("%c%f%d", &name, &price, &pages);
    }
    printf("what you entered:\n");

    for (i = 0; i <=2; i++) {
    printf("%c %f %d\n", name[i], price[i], pages[i]);
    }
    return 0;
}

这个程序来自《Let us C》一书,结构章节的第一页。

我的实际输出(我得到的)是:

Enter names, prices and pages of 3 books:

a 100 200 // given by me  
b 100 200

// but not able to give third index values

what you entered:

b 100.000000 200

84227675241280636545541341184\.000000 0

0\.000000 70

这是一个简单的程序,根据我的说法,我应该得到如下输出。

我的输出是我所期待的:

 Enter names, prices and pages of 3 books:

a 100 200  
b 100 200

c 100 200  

what you entered:

a 100.000000 200  
b 100.000000 200

c 100.000000 200
arrays c loops scanf
2个回答
2
投票

您应该在每次迭代时将数组的下一个元素的地址放入 scanf() 中,但是您每次都将地址传递给第一个元素而不是那个。 试着写:

scanf("%c%f%d", &name[i], &price[i], &pages[i]);

2
投票

数组

name
声明为

char name[3];

表达式

&name
具有
char ( * )[3]
类型,而转换说明符
c
需要相应的
char *
类型的参数。

还使用转换说明符输入字符

c
您需要跳过空格字符,例如按下 Enter 键后存储在输入缓冲区中的换行符
'\n'

所以你需要写

printf("Enter names, prices and pages of 3 books:\n ");
for (i = 0; i <=2; i++) {
    scanf( " %c%f%d", name + i, price + i, pages + i );
}

在此调用中,表达式

name + i
等同于
&name[i]
。同样适用于其他两个数组。

注意格式化字符串中的前导空格。它允许跳过空白字符。

使用像

3
2
这样的幻数也是一种糟糕的编程风格。相反,您可以引入一个命名常量,例如

enum { N = 3 };
char name[N];
float price[N];
int pages[N];

printf("Enter names, prices and pages of 3 books:\n ");
for ( i = 0; i < N; i++) {
    scanf( " %c%f%d", name + i, price + i, pages + i );
}
//...
© www.soinside.com 2019 - 2024. All rights reserved.