該程式應該要求您將成員(人員)添加到結構中并將它們列印到檔案上,但是在第一個 for 回圈之后停止作業并跳過名稱部分。我剛剛發現允許您向字串添加空格的東西,嘗試過但沒有成功......我試圖洗掉它并且它可以正常作業,所以[^\n]會出現問題。怎么了 ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Staff {
char Surname[100];
char Name[100];
int age;
char spec[100];
int id;
} person;
void write();
void leggi();
void trova();
int main() {
write();
}
void write() {
int i = 0;
int n = 1;
int r;
FILE *fp;
fopen_s(&fp, "index.txt", "w ");
if (fp == NULL) {
printf("Failed to open file\n");
exit(1);
}
fprintf(fp, "%d\n", i);
for (i = 0; i < n; i ) {
printf("Surame:\n");
scanf_s("%[^\n]s", person.Surname, 100);
fprintf(fp, "%s\t\t", person.Surname);
//loop just get over the name part
printf("Name:\n"); //after the first loop
scanf_s("%s", person.Name, 100);
fprintf(fp, "%s\t", person.Name);
printf("Age:\n");
scanf_s("%d", &person.age);
fprintf(fp, "%d\t", person.age);
printf("Specialization\n");
scanf_s("%s", person.spec, 100);
fprintf(fp, "%s\n", person.spec);
printf("Want to enter another? 1=yes 0=no...\n");
scanf_s("%d", &r);
if (r == 1)
n = n 1;
}
rewind(fp);
fprintf(fp, "%d\n", i);
fclose(fp);
}
uj5u.com熱心網友回復:
您的代碼中有多個問題:
您使用所謂的安全功能
fopen_s等scanf_s,但您不檢查回傳值以檢測無效輸入。您應該改用標準函式,傳遞適當的引數并檢查回傳值。using
scanf_s實際上是不可移植的:scanf_sC 標準附件 K 中定義的函式要求指標后面的長度引數具有size_t型別,而 Microsoft 庫中的同名函式使用 typeUINT,它在 64 位上具有不同的表示他們的 Windows 作業系統的版本。擁抱、增強和消滅策略的經典案例。在標準 C 中,應該寫:scanf_s("%s", person.Name, (size_t)100)或更好:scanf_s("%s", person.Name, sizeof person.Name)無需打開輸出檔案進行更新
"w ",只需使用"w".您將流指標倒回到檔案的開頭并覆寫檔案開頭的條目數。只要您的條目少于 10 個,此方法就有效,但除此之外,該數字有更多位數,因此檔案中的某些字符將被損壞。您可以使用帶有填充的格式,例如
"m\n"允許最多 100 萬條記錄而沒有風險。"%[^\n]s"不是正確的scanf格式:您應該只寫"%[^\n]"或更好"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481502.html上一篇:并行化三個嵌套回圈
