所以我正在嘗試創建一個將資料讀入檔案的程式。但在此之前,我需要將資料存盤到一個結構中。如何在結構中存盤字串?
#include <stdio.h>
#define MAX 100
int count;
struct cg {
float price;
char singer, song;
int release;
} hold[100];
int main() {
while (1) {
printf("Name of band of Singer: ");
scanf_s("%s,", &hold[count].singer);
printf("Name of Song: ");
scanf_s("%c", &hold[count].song);
printf("Price: ");
scanf_s("%f", &hold[count].price);
printf("Year of Release: ");
scanf_s("%d", &hold[count].release);
count ;
printf("\n");
}
}
uj5u.com熱心網友回復:
由于這里的問題是關于在 a 中存盤字串struct,這里是一個基本的解決方案:
#include <stdio.h>
#define MAX 100
int count;
struct cg {
float price;
char singer[20], song[20];
int release;
}hold[100];
int main() {
printf("Name of band of Singer: ");
fgets(hold[0].singer, 20, stdin);
printf("Singer: %s\n", hold[0].singer);
}
這個程式只是演示了在結構中存盤字串。這里,20是NUL您可以在singer或 中存盤的最大字符數(包括終止字符)song。或者,您還可以動態分配記憶體malloc()用于存盤字串。
請注意您的程式的其他幾個問題。例如,您的回圈永遠不會結束并且}缺少 a。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/338866.html
