How to read specifically formatted data from a file?

前端 未结 2 718
野的像风
野的像风 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:07

    perhaps this is what you want ?

    #include 
    #include 
    
    int main()
    {
    char str[200];
    FILE *fp;
    
    fp = fopen("test.txt", "r");
    while(fscanf(fp, "%s", str) == 1)
      {
        char* where = strchr( str, ':');
        if(where != NULL )
        {
          printf(" ':' found at postion %d in string %s\n", where-str+1, str); 
        }else
        {
          printf("COMMAND : %s\n", str); 
        }
      }      
    fclose(fp);
    return 0;
    }
    

    If output of it will be

    COMMAND : Add
     ':' found at postion 3 in string id:324
     ':' found at postion 5 in string name:"john"
     ':' found at postion 6 in string name2:"doe"
     ':' found at postion 5 in string num1:2009
     ':' found at postion 5 in string num2:5
     ':' found at postion 5 in string num2:20
    

提交回复
热议问题