[英]Not displaying all data in C using struct
所以我在 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 之間有一個逗號,這是不正確的。
或者也許可以使用具有緩沖區溢出保護的 fget 並使用 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 memory\n");
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] = '\0';
//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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.