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