gpt4 book ai didi

c - 如何用 cycle-for 和 scanf 填充我的结构数组的每个结构?

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:38 24 4
gpt4 key购买 nike

我是这个网站的新手,它看起来很酷。

我有这个问题,我想制作一个程序,让用户决定要申报多少本书,接下来用户为每本请求的书填写信息(例如:用户想要 3 本书,所以他填写了所有信息这 3 本书)。

我想我需要一个数组结构,但我不知道如何循环完成这个填充过程。

这是我的代码:

struct book
{
char bname[20];
int pages;
char author[20];
long price;
};

printf("enter number of books to store");
scanf("%d",&unumber);
for (i=0;i<number_of_books;i++) {printf's and scanf's to fill each struct}

最佳答案

在循环中读取输入时,一个主要的关注领域是确保 stdin 在每次读取后被刷新,以防止尾随的 newline 被解释为下一次的输入读取语句。有很多方法可以做到这一点,但是,使用 scanf 最简单的方法是通过精心设计的 format 语句来处理尾随的 newline。下面说明了这种方法:

#include <stdio.h>

#define MAXS 256

struct book
{
char bname[20];
int pages;
char author[20];
long price;
};

int main () {

struct book books[MAXS] = {{ {0}, 0, {0}, 0 }}; /* initialize all values to zero (null) */
int nbooks = 0;
int i = 0;

printf ("\nEnter number of books to store: ");
scanf("%d%*c",&nbooks); /* read nbooks, and consume newline */

if (nbooks < 1) { /* validate number of books to enter */
fprintf (stderr, "error: invalid entry for 'nbooks'\n");
return 1;
}

for (i = 0; i < nbooks; i++) /* enter values for each book, use */
{ /* scanf to read each value AND the */
printf ("\n book[%2d] name : ", i + 1); /* newline character, emptying stdin */
scanf ("%[^\n]%*c", books[i].bname); /* after each read. */
printf (" book[%2d] pages : ", i + 1);
scanf ("%d%*c", &books[i].pages);
printf (" book[%2d] author: ", i + 1);
scanf ("%[^\n]%*c", books[i].author);
printf (" book[%2d] price : ", i + 1);
scanf ("%ld%*c", &books[i].price);
}

printf ("\n\nThe Books Entered Were:\n"); /* output info for each book entered */
i = 0;
while (*books[i].bname)
{
printf ("\n Book %-3d \"%s\"\n", i + 1, books[i].bname);
printf (" author : %s\n", books[i].author);
printf (" pages : %d\n", books[i].pages);
printf (" price : %ld\n", books[i].price);
i++;
}

printf ("\n");

return 0;
}

输出:

$ ./bin/books

Enter number of books to store: 2

book[ 1] name : Tom Sawyer
book[ 1] pages : 321
book[ 1] author: Mark Twain
book[ 1] price : 2199

book[ 2] name : Huckelberry Finn
book[ 2] pages : 298
book[ 2] author: Mark Twain
book[ 2] price : 1999


The Books Entered Were:

Book 1 "Tom Sawyer"
author : Mark Twain
pages : 321
price : 2199

Book 2 "Huckelberry Finn"
author : Mark Twain
pages : 298
price : 1999

关于c - 如何用 cycle-for 和 scanf 填充我的结构数组的每个结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com