我正在尝试使用struct创建一个类似于“ bank”的程序,但是当程序应该读取字符串(葡萄牙语中的变量“ nome”即名称)时,它完全忽略了我使用的“ fgets”。这是我正在谈论的部分:
printf("\nNome: \n");
fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);
而且我非常确定,问题可能出在对象数组的动态分配上。请帮我解决这个问题,谢谢!
PS:对不起,但是代码是葡萄牙语(我的母语)。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
/*
Programa realiza uma alocacao dinamica por meio
de uma funcao que recebe a dimensao e retorna o vetor(ponteiro)
*/
struct CLIENTES
{
int ano_nasc, cpf[11];
float renda_m;
char nome[50];
}; //Lista de Objetos
int main(void)
{
//Declaracao de Variaveis
int cont=0, num, num_2, client, i, j;
CLIENTES *vet;
//Leitura de Dados
printf("Digite o numero de Clientes: ");
scanf("%d", &num);
vet = (CLIENTES*)malloc(num*sizeof(int));
printf("Digite os Dados do Cliente.");
while (cont != num)
{
printf("\nNome: \n");
fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);
printf("\nAno de Nascimento: ");
scanf("%d", &vet[cont+1].ano_nasc);
printf("\nCPF: ");
scanf("%d", &vet[cont+1].cpf);
printf("\nRenda Mensal: ");
scanf("%d", &vet[cont+1].renda_m);
cont++;
}
printf("\nDigite o numero do cliente que voce deseja conferir: ");
scanf("%d", &num_2);
for (i=0;i<num;i++)
{
if(num_2 == num)
{
printf("\nO que deseja saber sobre ele?\n");
printf("1-Nome\n2-Ano de Nascimento\n3-CPF\n4-Renda Mensal\n\n\n");
scanf("%d", &client);
if (client == 1)
{
printf("Nome: %c", vet[num_2].nome );
}
else if(client == 2)
{
printf("Ano de Nascimento: %d", vet[num_2].ano_nasc );
}
else if(client == 3)
{
for(j=0;j<11;j++)
{
printf("CPF: %d", vet[num_2].cpf[j]);
}
}
else if(client == 4)
{
printf("Renda Mensal: %f", vet[num_2].renda_m );
}
}
}
//Finalizando o Programa
printf("\n\nFim do Programa!");
getch();
return 0;
}
我看到的问题:
您在该行中分配了错误的内存量:
vet = (CLIENTES*)malloc(num*sizeof(int));
应该是:
vet = malloc(num*sizeof(*vet));
请参见是否强制转换malloc的结果?。答案解释了为什么不应该转换的返回值malloc
。
您正在使用fgets
后scanf
。scanf
将换行符和其他空白字符留在流中。fgets
之后立即调用when时,fgets
仅读取空白和换行符。您需要添加代码,以忽略调用之后scanf
和之前的其余行fgets
。
// Skip everything up to and including the newline.
int c;
while ( (c = getc(stdin)) != EOF && c != '\n');
在那之后,
fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);
应该正确读取数据。
您在该行中使用了错误的值:
scanf("%d", &vet[cont+1].cpf);
cpf
是上的数组int
。如果您只想阅读一本int
,可以使用:
scanf("%d", &vet[cont+1].cpf[0]);
您在该行中使用了错误的格式说明符:
scanf("%d", &vet[cont+1].renda_m);
它应该是:
scanf("%f", &vet[cont+1].renda_m);
// ^^ %f not %d
您使用错误的索引访问数组vet
。您在任何地方使用vet[cont+1]
它都应该vet[cont]
。通过使用vet[cont+1]
,您没有使用数组的第一个元素vet[0]
,并且访问的内存超出了您通过访问分配的内存vet[num]
。
如果解决上述问题,则程序可能会运行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句