不使用结构显示C中的所有数据



所以我用C编写了一个简单的程序来帮助我理解结构。它没有什么太复杂的地方。但是,当它到达应该显示数据的位置时,它只显示部分数据。该程序要求用户输入名字和姓氏,然后输入金额。然后它应该显示名字和姓氏,以及金额。它不显示姓氏。我确信这可能是一件简单的事情,但我不确定我在这里错过了什么。

这是代码:

#include <stdio.h>
#include <stdlib.h>
#define NAMESIZE 30 
struct data{
float amount;
char firstName[NAMESIZE];
char lastName [NAMESIZE];
}record;
int main()
{
printf("nEnter the donor's first and last names n");
printf("Separate names by a space: ");
scanf("%s, %s", record.firstName, record.lastName);

char c;
while ( (c = getchar()) != 'n' && c != EOF )
{
}

// At this point the program does not work correctly
// It will just print the first name not the last name
printf("nEnter the donation amount: ");
scanf("%f", &record.amount);
// Display the information
printf("nDonor %s %s gave $%.2f n", record.firstName, record.lastName, record.amount);
return 0;
}

如有任何建议,我们将不胜感激。谢谢

一旦我在第一次scanf调用中去掉了多余的逗号,它就起了作用。这是被更正的行:

scanf("%s %s", record.firstName, record.lastName);

我在两个%s之间有一个逗号,这是不正确的。

或者可以使用缓冲区溢出保护的fgets,并使用strtok来分割的间距

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMESIZE 30 
struct data{
float amount;
char firstName[NAMESIZE];
char lastName [NAMESIZE];
}record;
int main()
{
char *name = malloc(NAMESIZE);
if (name == NULL) {
printf("No memoryn");
return 1;
}
printf("nEnter the donor's first and last names n");
printf("Separate names by a space: ");
//scanf("%s, %s", record.firstName, record.lastName);
fgets(name, NAMESIZE, stdin);
if ((strlen(name) > 0) && (name[strlen (name) - 1] == 'n'))
name[strlen (name) - 1] = '';
//split name
int init_size = strlen(name);
char delim[] = " ";
char *ptr = strtok(name, delim);
int idx = 0;
while(ptr != NULL)
{
printf("%d '%s'n",idx, ptr);
if(idx == 0){
strcpy(record.firstName, ptr);
}
else{
strcpy(record.lastName, ptr);
}
ptr = strtok(NULL, delim);
idx += 1;
}
/*
char c;
while ( (c = getchar()) != 'n' && c != EOF )
{
}
*/
// At this point the program does not work correctly
// It will just print the first name not the last name
printf("nEnter the donation amount: ");
scanf("%f", &record.amount);
// Display the information
printf("nDonor %s %s gave $%.2f n", record.firstName, record.lastName, record.amount);
free(name);
return 0;
}

最新更新