簡體   English   中英

從每一行,從c中的文件中逐字保存

[英]saving word by word ,from each line , from a file in c

假設我們在文件中有一些聯系人,例如一本小電話簿。

我想制作一個像在線電話簿一樣工作的小程序,文本中的每個聯系人都占用Line的大小,並且信息的放置順序如下: NAME SURNAME ADRESS PHONE ,但是每個電話的數量接觸可以超過一個。 因此,例如:

 George Mikels "green str" 123123 12121232 
 Maria Luis "olive str" 6548845

到目前為止,我已經嘗試過:

void Createtree(node **head_node)
{
    int count=0,*phones;
    char filename[50], name[30], surname[50], adress[70];
    char c;

    FILE *fp;
    printf("PLease enter the name of the file\n");
    scanf("%s", &filename);

    fp = fopen("text.txt", "r");
    if(fp == NULL)
    {
        printf("failed to open file");
        return ;
    }

    do
    {
        c=fscanf(fp, "%s %s %s ", &name, &surname, &adress);

        //takes the name ,surname and adress
        printf(" %s %s %s\n", &name, &surname, &adress);
        phones = (int*)malloc(sizeof(int));

        //creates a dynamic array of int in order to save the phones
        do
        {
            //saves each Number inside the array
            c = fscanf(fp, " %d ", phones[count]);
            count = count + 1;

            phones = (int*)realloc(phones, (count +1) * sizeof(int));

            // increases the size of the array in order to save all the phones 
        }while(c != '\n');

        //does it until the end of the Line 
        count=0;

        Insert(head_node,name,surname,phones);
        //uses a function to add the Information to a list 

    }while(c != EOF);
};

我無法將手機保存在陣列中,也不知道為什么。

嘗試在讀取之前分配數組,然后實際讀取將初始化數組的元素。

// define max number size
int maxSizeOfNumber = 20;

// allocate dynamic memory
int *phones = malloc(maxSizeOfNumber * sizeof(int));

// read phone number
do {

    c = fscanf(fp, "%d", &phones[count]);
    count++;

} while (c > 0 && count < maxSizeOfNumber );

我建議您將電話號碼存儲在字符數組或字符串中,以避免將數字存儲在int ,例如,以0開頭的數字,如@Bob__的注釋部分所述。

暫無
暫無

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

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