【问题标题】:Struct with scanf and file用 scanf 和文件构建结构
【发布时间】:2014-12-08 21:34:54
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

    struct data {
        char *first;
        char *last;
        int age;
        char *email;
        int bday[3];
    };

typedef struct data id;


void id_read(){
        FILE *fp;

为此目的创建文件

        fp=fopen("Data.txt" , "w");

读取数据并将其打印到文件中

        printf("Give First name please: ");
             scanf("%s" , &(id.first));
        fprintf( fp , "First name: %s" , id.first);
        printf("\nGive Last name please: ");
             scanf("%s" , &(id.last));
        fprintf(fp ,"\nLast name: %s" , id.last);
        printf("\nGive your email: ");
             scanf("%s" , &(id.email));
        fprintf(fp , "\nEmail: %s" , id.email);
        printf("\nGive birthday date: ");
        printf("\nDay: ");
             scanf("%d" , &id.bday[0]);
        printf("\nMonth: ");
             scanf("%d" , &(id.bday[1]));
        printf("\nYear: ");
             scanf("%d" , &(id.bday[2]));
        fprintf(fp ,"\nBirthdate: %d/%d/%d" , id.bday[0] , id.bday[1] , id.bday[2]);
        printf("\nGive your age: ");
             scanf("%d", &(id.age));
        fprintf(fp , "\nAge: %d" , id.age);
        fclose(fp);
}

主要功能

 int main(){
        printf("Give your ID carefully! \n\n");
        id_read();
        return 0;
 }

scanf 的编译器错误。

 [Error] expected expression before ')' token.
 [Error] expected ')' before '.' token

【问题讨论】:

    标签: c file struct


    【解决方案1】:

    两件事。

    id 是 typedef 数据类型,而不是变量本身。需要有一个id 类型的变量,比如id input。那么,

    1. 需要使用malloc()为指针input.first分配内存。
    2. scanf("%s" , &amp;(id.first));需要改为scanf("%s" , input.first);

    其他指针变量也一样。

    【讨论】:

    • 我更正了这一点,并且程序可以正常工作,直到必须扫描电子邮件为止。然后程序崩溃!你知道为什么会这样吗?非常感谢!
    • 你分配了内存?什么大小的?内存应该足够大,可以容纳一个大的电子邮件 ID,比如thisisanexampleoflargeemailid@verylargeemailidprovider.co.in
    • 即使我使用的是字符串指针,我也必须这样做?为什么这不是第一次或最后一次发生?
    • @konstantinos 是的。不分配内存,怎么往里面存东西?
    • 我用指针存储第一个和最后一个而不分配内存
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多