How to read specifically formatted data from a file?

前端 未结 2 692
野的像风
野的像风 2021-01-19 06:30

I\'m supposed to read inputs and arguments from a file similar to this format:

Add  id:324  name:\"john\" name2:\"doe\" num1:2009 num2:5 num2:20
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 07:18

    If you know for sure the input file will be in a well-formed, very specific format, fscanf() is always an option and will do a lot of the work for you. Below I use sscanf() instead just to illustrate without having to create a file. You can change the call to use fscanf() for your file.

    #define MAXSIZE 32
    const char *line = "Add  id:324  name:\"john\" name2:\"doe\" num1:2009 num2:5 num3:20";
    char op[MAXSIZE], name[MAXSIZE], name2[MAXSIZE];
    int id, num1, num2, num3;
    int count =
        sscanf(line,
            "%s "
            "id:%d "
            "name:\"%[^\"]\" "  /* use "name:%s" if you want the quotes */
            "name2:\"%[^\"]\" "
            "num1:%d "
            "num2:%d "
            "num3:%d ", /* typo? */
            op, &id, name, name2, &num1, &num2, &num3);
    if (count == 7)
        printf("%s %d %s %s %d %d %d\n", op, id, name, name2, num1, num2, num3);
    else
        printf("error scanning line\n");
    

    Outputs:

    Add 324 john doe 2009 5 20

    Otherwise, I would manually parse the input reading a character at a time or or throw it in a buffer if for whatever reason using fgets() wasn't allowed. It's always easier to have it buffered than not IMHO. Then you could use other functions like strtok() and whatnot to do the parse.

提交回复
热议问题