簡體   English   中英

為什么它跳過fgets()?

[英]Why does it skip fgets()?

typedef struct {
int serial_no;
char s_name[100];
char s_street[50];
char s_town[20];
int s_speaker_no;
int max_no_teachers;
int no_applied_teachers;
} type_seminar;


void add_seminar() {
int seminar_number, temp_int;
char *temp_string;
temp_string = (char*) malloc(100 * sizeof(char));

FILE *f_sem;
FILE *f_school;
f_sem = fopen("seminars.bin", "a");
f_school = fopen("school_list.txt", "r");

fgets(temp_string, 10, f_school);
seminar_number = (atoi(temp_string) + 1);

type_seminar *temp_s = (type_seminar*) malloc(sizeof(type_seminar));
temp_s->serial_no = seminar_number;
temp_s->no_applied_teachers = 0;
temp_s->s_speaker_no = 0;

printf("Enter the seminar title: \n");
fgets(temp_string, sizeof temp_string, stdin);
strcpy(temp_s->s_name, temp_string);

printf("Enter the seminar address(street and house number): \n");
fgets(temp_string, sizeof temp_string, stdin);
strcpy(temp_s->s_street, temp_string);

printf("Enter the town (where the seminar will be held) : \n");
fgets(temp_string, sizeof temp_string, stdin);
strcpy(temp_s->s_town, temp_string);

printf("Enter the maximum number of the seminar participants : \n");
fgets(temp_string, sizeof temp_string, stdin);
temp_int = (atoi(temp_string));
temp_s->max_no_teachers = temp_int;

free(temp_s);
free(temp_string);
fclose(f_school);
fclose(f_sem);
}

每次我運行函數時,用戶應輸入研討會標題的第一個fgets()都會被跳過。 我假設從txt文件讀取的previus fgets()在緩沖區中保留了某些內容? 我不知道如何解決這個問題……而且,我是C和一般編程領域的新手,所以如果它有點麻煩的話……抱歉:/

榮譽使用fgets避免緩沖區溢出,但你不太有:

char *temp_string;
:
temp_string = (char*) malloc(100 * sizeof(char));
:
fgets(temp_string, sizeof temp_string, stdin);

temp_string的大小是char指針的大小而不是您分配的緩沖區的大小。 這意味着您很可能最多讀取四個字符(如果有64位指針,則可能最多讀取八個字符),然后其余字符留在輸入流中。

您應該使用緩沖區的大小(100,盡管將其作為定義的常量而不是硬編碼的值會更好)。

或者,查看此getLine例程 ,該例程可以處理很多邊緣情況。


而且,順便說一句,您不需要乘以sizeof(char)因為根據定義始終保證為1進行乘法只會阻塞源代碼。

您也不應該轉換malloc的返回值,因為它可以隱藏某些細微的錯誤。 C是相當能夠隱式轉換the空隙*`返回值的任何其他指針類型。

您應該注意的另一件事:即使您使用fgets保護temp_string緩沖區temp_string溢出,但對於strcpy函數卻沒有temp_string類似的保護措施。

這意味着它將允許您輸入一個80個字符的城鎮名稱,然后將其strcpy到20個字符的結構字段中后,該內存將被吹走。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM