【问题标题】:C - Reading strings from text file into arrays inside a structureC - 将文本文件中的字符串读取到结构内的数组中
【发布时间】:2021-04-29 12:33:16
【问题描述】:

我正在尝试将 .txt 文件中的文本读取到结构数组中。 这是我的代码(我已经玩过这个堆,如果它看起来到处都是,请道歉):

#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

非常感谢您的帮助。

【问题讨论】:

  • users = &amp;userList; --> users = userList;
  • 问题/问题是什么?
  • Unable to open users.txt 不是有用的错误消息。试试perror("users.txt");
  • 每一行输入有3个值。为什么scanf格式字符串有4次转换?
  • 请注意scanf 格式%s 永远不会包含任何类型的空格(包括换行符)。另一方面,它将读取并忽略(丢弃)前导空格。

标签: arrays c struct


【解决方案1】:

您只需要 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);

【讨论】:

  • 我实现了这些更改,我得到的输出对于第一行是正确的。当我尝试输出第二行5678 Barry Cool 时,它似乎没有存储在 userList 结构中?它打印出PIN □#□☺| First | Last ↑♣|
  • @BlackSolis 在您显示的代码中,您只读取了第一行,因此数组的第二个条目保持未初始化。在不知道你实际使用什么代码的情况下很难回答这个问题,但我猜你没有实现循环,也从未阅读过第二行。
  • 谢谢@William Pursell - 你是对的,我从主代码中提取了这个来排除故障,我把循环抛在脑后......非常感谢先生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
相关资源
最近更新 更多