简体   繁体   English

fscanf从c文件中的一行

[英]fscanf a line from file in c

I have a file that i need to read from into certain variables. 我有一个文件,我需要从中读取某些变量。 The information is stored in the file with a delimiter ; 信息以定界符存储在文件中; that separates between each bit of information. 在每条信息之间进行分隔。 for example: 例如:

308163583 ;Adam ;Fro ;22;M ;mogar ;mmMM8675 ;like to walk on the beach ;1,2,3,4; 308163583;亚当;来; 22;男;莫加; mmMM8675;喜欢在沙滩上散步; 1,2,3,4;

afterwards i'm going to place that information into a structure but that's not relevant now. 之后,我将把这些信息放入一个结构中,但是现在不相关了。 the problem is that it scans everything fine until "like to walk on the beach" and it stops at "like" and only scans this word into description string 问题是它会扫描一切正常,直到“喜欢在沙滩上走”,然后停在“喜欢”,然后仅将此词扫描到描述字符串中

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXID 10
#define MAXN 11
#define MAXPAS 7
#define MAXDES 201
#define MAXHOB 4
#define MAXGEN 2
typedef enum { false, true } bool;
typedef struct {

    char* id;
    char* fname;
    char* lname;
    int age;
    char* gender;
    char* username;
    char* password;
    char* description;
    int hobbies;
}User;
typedef struct {
    User *users;
    int num_users;
}List;

void inputFunction(FILE *ifp);
void main() {
    FILE *ifp;
    char mode[] = "r";
    ifp = fopen("input.txt", mode);
    if (ifp == NULL) {
        puts("Can't open input file");
        exit(1);
    }
    inputFunction(ifp);
}

void inputFunction(FILE *ifp) {
    List userList;
    userList.users = (User*)malloc(1 * sizeof(User));
    int i = 0;
    char id[MAXID], fname[MAXN], lname[MAXN], gender[MAXGEN],
       username[MAXN], password[MAXPAS], description[MAXDES];
    int age, hobbies[MAXHOB];
    while (fscanf(ifp, "%s ;%s ;%s ;%d;%s ;%s ;%s ;%s;%d,%d,%d,%d", id,
      fname, lname, &age, gender, username, password, description,
      &hobbies[0], &hobbies[1], &hobbies[2], &hobbies[3])!=EOF)
    {

    }
}

That's because scanf's %s is specified as Matching a sequence of non-white-space characters . 这是因为scanf的%s被指定为匹配一系列非空白字符 You want it to scanf for a sequence of non-semicolon characters . 您希望它扫描一系列非分号字符 Left as an exercise :-) Hint: read the manual and see how the %[...] specifier works. 留作练习:-)提示:请阅读手册,并查看%[...]指示符的工作方式。

Also note that 另请注意

while (fscanf(...) != EOF)

is a colossal bug, since fscanf returns the number of successfully converted items, ie 0 if nothing was converted and 12 if all items were converted. 是一个巨大的错误,因为fscanf返回成功转换的项目数,即如果没有转换,则返回0,如果所有项目都转换,则返回12。 Testing for EOF you can't detect if less than 12 items where correctly converted. 测试EOF,您将无法检测到是否正确转换的项目少于12个。 You should seriously consider reading the scanf/fscanf manual from top to bottom. 您应该认真考虑从上至下阅读scanf / fscanf手册 It is quite instructive and will prove valuable time and again over your whole programming career. 这是很有启发性的,并且将在您整个编程生涯中一次又一次地证明宝贵的时间。

You could use the strtok function to split the line using your own set of delimiters. 您可以使用strtok函数使用自己的定界符集来分隔行。

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
    const char delims[] = ";"; //List of delimiters
    char str[] = "308163583 ;Adam ;Fro ;22;M ;mogar ;mmMM8675 ;like to walk on the beach ;1,2,3,4;";
    char * pch;
    // Split the string at specified set of delimters
    pch = strtok (str,delims);
    while (pch != NULL)
    {
        // Do whatever you need to process the token here
        printf ("%s\n",pch);

        // Find the next token
        pch = strtok (NULL,delims);
    }
    return 0;
}

Normally, scanf() function read the string up to the white space character only. 通常,scanf()函数仅读取字符串,直到空白字符为止。 You should try with strtok() function for getting the stream up to the specified delimiter. 您应该尝试使用strtok()函数来使流达到指定的分隔符。

@Jens: For the current assignment I don't require checking that all fields are correct, it is given. @Jens:对于当前作业,我不需要检查所有字段是否正确,即已给出。 Found a different solution: 找到了不同的解决方案:

List loadFile(FILE *ifp) {
    int i = 0;
    List userList;
    userList.users = NULL;
    char id[MAXID], fname[MAXN], lname[MAXN], gender[MAXGEN], username[MAXN], password[MAXDES], description[MAXDES];
    int age, hobbies[MAXHOB];
    while (fscanf(ifp, "%s ;%s ;%s ;%d;%s ;%s ;%s ;%200[^;];%d,%d,%d,%d;\n", id, fname, lname, &age, gender, username, password, description, &hobbies[0], &hobbies[1], &hobbies[2], &hobbies[3]) != EOF)
    {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM