繁体   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