[英]C - Reading strings from text file into arrays inside a structure
I am trying to read text from a.txt file into arrays of a structure.我正在尝试将 a.txt 文件中的文本读取到结构的 arrays 中。 This is my code (I have played around with this a heap so apologies if it seems all over the place):
这是我的代码(我已经玩过这个堆,所以如果它看起来到处都是道歉):
#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;
}
The users.txt file contains the text: users.txt 文件包含以下文本:
1234 John Smith
5678 Barry Cool
Many thanks for the help.非常感谢您的帮助。
You only want 3 conversion specifiers in the scanf.您只需要 scanf 中的 3 个转换说明符。 Try
尝试
if( 3 == fscanf(filePtr, "%4s %25s %25s", users[i].pin, users[i].first, users[i].last) ){ ...
The printf is also weird. printf 也很奇怪。 Try:
尝试:
printf("PIN %s| First %s| Last %s|", users[i].pin, users[i].first, users[i].last);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.