快速预订问题

扫码查看
本文介绍了快速预订问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

这code后,我选择一个条目后,我把一个条目和preSS进入它崩溃说堆栈各地变量'项目'已损坏。我相当有信心,这是我用我的fwrite功能。我所知道的第一个参数FWRITE查找要写入指针元素的数组,但我认为我只是困惑现在。任何帮助将是非常美联社preciated。

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);

你想读一个字符串和一个数字,并将其存储在字符。他们都应该是

scanf("%c", &choice);

这是说,你应该考虑重写这个使用 ifstream的 CIN 函数getline 的std ::字符串,让您的生活更轻松,如果你不寻求最大性能。

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.

这篇关于快速预订问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 18:22
查看更多