Home > database >  C split specific File input into variables
C split specific File input into variables

Time:03-25

I'm making phone book assignment. I have to get data from delivered file that is given in specific format. Name | Surname | Phone number I'm using code below :

    while(!feof(file)){
        int result = fscanf(file, "s | 9s | %d", p->name, p->last_name, &p->number);
        if (result == 3){
            p  ;
            counter  ;
            if (counter > size   1){
                break;
            }
        }
    }

It works ok for simple cases like : Jim | Carrey | 123456 but it breaks when input is Louis | Gossett Jr. | 502521950 Then this function writes name Louis Surname Gossett(lacks " .Jr" and Phone number is left empty and result returns 2 which makes input invalid... How can i fix this ?

I tried to play a little bit with format specifiers [^...] but I can't really figure out if that's the correct way of thinking and how they actually works. Whenever i added something, everything broke completely. I'll add that requirement is not to use Arrays or functions allocating memory :(

CodePudding user response:

Fscanf with %s format specifier will read a word and stop when it encounters a whitespace (newline, space or tab). That is why surname is not read completely. You are reading Luis and Gossett but %d can't read a string Jr.

You could use %[^|]| to read the whole string (name or surname).

Try fscanf(file, "[^|]|9[^|]|%d", p->name, p->last_name, &p->number);

Something like this after fscanf call should clear the trailing spaces, but there are probably other ways to do it.

if (p->name[strlen(p->name)-1] == ' ')
   p->name[strlen(p->name)-1] = '\0';
  • Related