我正在尝试用 C 语言制作帐户系统。 我正在尝试这种方式来向结构数组进行输入。
struct account { // Account Structure
int id;
int money;
char *name[30];
};
account * accountarray[50];
int number;
void MakeAccount() {
int id;
int input_money;
char name[50];
printf("--Make Account--\n");
printf("Input ID : ");
scanf("%d", &id);
printf("Insert Money : ");
scanf("%d", &input_money);
printf("Your Name? : ");
scanf("%s", name);
accountarray[number++] = NULL; // I think there's a problem in this side
accountarray[number++]->id = id;
accountarray[number++]->money = input_money;
*accountarray[number++]->name = name;
}
当我输入值时它会停止...我认为下面的 4 个代码有问题.. 有什么好的办法可以让它变得更好吗?
最佳答案
这是您的代码版本。
- 编译干净
- 它不可执行,因为没有
main()
函数 - 它正确执行错误检查
- 它正确地将错误消息输出到
stderr
- 它正确声明了“帐户”数据数组
- 它适本地使用空行来对代码块和事件 block 进行分组
- 它正确地使用字符串函数来复制
name
数组 - 发生错误时退出程序
- 程序缩进保持一致,易于阅读
- 它为“神奇”数字提供了有意义的名称(并在整个代码中使用这些有意义的名称
- 它避免了输入缓冲区溢出的任何可能性
- 它包含必要的头文件和注释为什么包含每个头文件
- 它不会消耗用户输入的最终“换行”序列,但是,对
id
调用scanf()
将消耗剩余的字节( s) 在stdin
中作为输入下一个帐户时的“%d”输入/转换说明符,将消耗前导空格
现在是代码
#include <stdio.h> // printf(), scanf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <string.h> // strcpy()
// eliminate 'magic' numbers
#define MAX_STR_LEN 30
#define MAX_ACCTS 50
// define the struct
struct account
{ // Account Structure
int id;
int money;
char name[ MAX_STR_LEN ];
};
// prototypes
void MakeAccount( void );
// === file global data ===
// declare MAX_ACCTS instances of the struct
struct account accountarray[ MAX_ACCTS ];
// declare a counter
int number = 0;
void MakeAccount()
{
int id;
int input_money;
char name[ MAX_STR_LEN ];
int scanfStatus;
printf("--Make Account--\n");
printf("Input ID : ");
scanfStatus = scanf("%d", &id);
if( 1 != scanfStatus )
{ // then scanf failed
// output error message, including the OS reason for the error to 'stderr'
perror( "scanf for account id failed" );
exit( EXIT_FAILURE );
}
//implied else, scanf successful
printf("Insert Money : ");
scanfStatus = scanf("%d", &input_money);
if( 1 != scanfStatus )
{ // then scanf failed
// output error message, including the OS reason for the error to 'stderr'
perror( "scanf for account money failed" );
exit( EXIT_FAILURE );
}
printf("Your Name? : ");
scanfStatus = scanf("%29s", name); // note MAX CHARACTERS 1 less than length of input buffer
if( 1 != scanfStatus )
{ // then scanf failed
// output error message, including the OS reason for the error to 'stderr'
perror( "scanf for account name failed" );
exit( EXIT_FAILURE );
}
accountarray[number].id = id;
accountarray[number].money = input_money;
strcpy( accountarray[number].name, name);
} // end function: MakeAccount
关于c - 如何将值放入数组结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289868/