我有一个for循环,它遍历struct类型的数组,但当我将用户输入传递给检索值的函数时,它会打印出10次。我需要我的main((询问用户要打印地址簿的哪个#,这样它就会被传递给打印它的函数,但函数会检查数组中是否有这样的数字,如果有,它就会打印出输入的#的值。以下是持续打印printAddress((十次的代码:
STRUCTURE FOR
struct addressBook
{
int entryNum;
char name[100];
char address[100];
};
void printAddress(struct addressBook addresses, int num)
{
int n = 0;
for(n=0; n < 10; n++)
{
if (addresses.checkNum == num)
{
printf("nBELOW IS ADDRESS # %i DETAILS: n", num);
printf("Address Book Number: %i n", addresses.entryNum);
printf("Name: %s", addresses.name);
printf("Address: %s n", addresses.address);
}
}
}
my main function:
int main()
{
// create a addressBook array of at least 10
struct addressBook addresses[10];
//if statements where user can select to
//add a name to address book, display a single name or quit the program
//this is if they choose to display a single name using a number
else if (choice == 2)
{
int num;
int i = 0;
printf("Enter book number: ");
scanf("%i", &num);
printAddress(addresses[i], num);
}
return 0
}
下面是对您的代码的改编,它似乎可以像我所期望的那样工作:
#include <stdio.h>
struct addressBook
{
int entryNum;
char name[100];
char address[100];
};
static
void printAddress(int n_addr, struct addressBook addresses[n_addr], int num)
{
for (int n = 0; n < n_addr; n++)
{
if (addresses[n].entryNum == num)
{
printf("nBELOW IS ADDRESS # %i DETAILS:n", num);
printf("Address Book Number: %in", addresses[n].entryNum);
printf("Name: %sn", addresses[n].name);
printf("Address: %sn", addresses[n].address);
}
}
}
int main(void)
{
struct addressBook addresses[10] =
{
{ 1, "John Doe", "1234 Any St, Some Town, CA 94301" },
{ 2, "Mary Fog", "1270 Some St, Any Town, CA 94303" },
{ 3, "Anne Pit", "1240 Any Rd, Some City, CA 94301" },
{ 4, "Bill Zoo", "1252 Some St, Any Town, CA 94303" },
{ 5, "Phil Tin", "1258 Any Rd, Some City, CA 94301" },
};
int num;
printf("Entry number? ");
scanf("%i", &num);
printAddress(5, addresses, num);
return 0;
}
您可以在函数中if
的主体中打印后添加return;
或break;
。如果添加return;
,则可以添加'printf("条目%d未找到\n",num(;`在循环之后和函数返回之前。
请注意,您通常不希望换行前有空格;后面的空格很草率。此外,现在名称后面有一个换行符;如果您将名称运行到标签Address:
中,它看起来很难看。
给定从addr83.c
编译的程序addr83
,运行示例为:
$ addr83
Entry number? 4
BELOW IS ADDRESS # 4 DETAILS:
Address Book Number: 4
Name: Bill Zoo
Address: 1252 Some St, Any Town, CA 94303
$