簡體   English   中英

C - 將文本文件中的字符串讀取到結構內的 arrays

[英]C - Reading strings from text file into arrays inside a structure

我正在嘗試將 a.txt 文件中的文本讀取到結構的 arrays 中。 這是我的代碼(我已經玩過這個堆,所以如果它看起來到處都是道歉):

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#include <string.h>
#include <ctype.h>

int main()
{
    int i = 1;
    int j = 0;

    char temp[4];

    struct userStruct {             // a struct definition for the users;
        char pin[5];
        char first[26];
        char last[26];
    };
    struct userStruct userList[10];     // an array of struct user to hold 10 users
    struct userStruct * users;
    users = &userList;

    FILE * filePtr;

    filePtr = fopen ("users.txt", "r");
    if (filePtr != NULL)
    {
        fscanf(filePtr, "%s %s %s %s", users[i].pin[j], users[i].first[j], users[i].last[j], temp);
        if (strcmp(temp, "\n"))
        {
            i++;
            j++;

        }
        printf("PIN %s| First %s| Last %s|", users[i].pin[j], users[i].first[j], users[i].last[j]);

        fclose(filePtr);
    }
    else
    {
        printf("Unable to open users.txt");
    }
    return 0;
}

users.txt 文件包含以下文本:

1234 John Smith
5678 Barry Cool

非常感謝您的幫助。

您只需要 scanf 中的 3 個轉換說明符。 嘗試

if( 3 == fscanf(filePtr, "%4s %25s %25s", users[i].pin, users[i].first, users[i].last) ){ ...

printf 也很奇怪。 嘗試:

printf("PIN %s| First %s| Last %s|", users[i].pin, users[i].first, users[i].last);

暫無
暫無

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

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