快速预订问题 [英] Quick booking issue
问题描述
#include <stdio.h>
#pragma pack(push)
#pragma (1)
typedef struct contact {
char firstname [40];
char lastname [40];
char address [100];
char phone[10];
}contact;
#pragma pack(pop)
int main ()
{ FILE *pFile;
contact entry = {"", "", "", ""};
char choice;
pFile = fopen("C:\\contacts.txt", "w+");
if(!pFile){
printf("File could not be open");
return 1;
}
printf("Choose a selection\n\n");
printf("1. Enter First Name\n");
printf("2. Enter Last Name\n");
printf("3. Enter Address\n");
printf("4. Enter Phone Number\n\n");
scanf( "%d", &choice);
switch (choice){
case 1:
printf("First name: \n");
fgets(entry.firstname, sizeof(entry.firstname),pFile);
break;
case 2:
printf("Last name: \n");
fgets(entry.lastname, sizeof(entry.lastname),pFile);
break;
case 3:
printf("Address: \n");
fgets(entry.address, sizeof(entry.address),pFile);
break;
case 4:
printf("Phone Number: \n");
fgets(entry.phone, sizeof(entry.phone),pFile);
break;
default:
printf(" No Choice selected, Ending Address Book Entry system");
break;
}
fwrite(&entry, sizeof(contact), 1, pFile);
printf("Enter a new contact?");
scanf("%s", &choice);
//while(choice != 'n');
fclose(pFile);
getchar();
return 0;
}
这段代码在我选择一个条目后,输入它崩溃说堆栈变量'条目'已损坏。我相信,这是我的fwrite函数,我使用。我知道第一个参数fwrite寻找是一个指向要写的元素数组的指针,但我想我现在只是困惑。
This code after I choose an entry and after I put an entry in and press enter it crashes saying Stack around the variable 'entry' was corrupted. I'm fairly confident that it is my fwrite function that I'm using. I know the first parameter fwrite looks for is a pointer to an array of elements to be written but I think I'm just confused right now. Any help would be much appreciated.
推荐答案
您应该更改所有
fgets(entry.firstname, sizeof(entry.firstname),pFile);
到
fgets(entry.firstname, sizeof(entry.firstname),stdin);
因为您正在从控制台阅读,而不是文件。
Because you're reading from the console, not the file.
此外,使用
scanf("%s", &choice);
和
scanf( "%d", &choice);
您尝试读取字符串和数字并将其存储在 char
。它们都应为
you're trying to read a string and a digit and store it in a char
. They both should be
scanf("%c", &choice);
也就是说,你应该考虑使用 ifstream
, cin
, getline
和 std :: string
让您的生活更轻松,如果你不寻求最大的性能。
That said, you should think about rewriting this using ifstream
, cin
, getline
, and std::string
to make your life easier if you're not looking for maximum performance.
这篇关于快速预订问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!