Home > other >  Problem with sscanf not reading the 3 variables i want in C
Problem with sscanf not reading the 3 variables i want in C

Time:12-18

I have an .txt with "323,John of Sea,11.2" (ignore the ")

and i want to read this and then divide it into 3 variables like: int number1 / char Name[100] / float number2

#include <stdio.h>

int main()
{
    int number1;
    float number2;
    char Name[100],Phrase[100];
    FILE *inf ;
    
    if((inf = fopen("Information.txt","r")) == NULL){
        printf("Erro!\n");
    }
    
    while (fgets(Phrase,100,inf) != NULL )
    {   
        sscanf(Phrase , "%d,%s,%f", &number1 , Name, &number2 ); 
        printf("%d  %s  %f \n", number1, Name, number2);   
    }
    
}
323,John of Sea,11.2

Well the problem is when i compile everthing it gives me 323 John 0.000000 an it should give me 323,John of Sea,11.2 i have tried many things but nothing seems to work. IMPOTANT = It needs to be separeted in 3 varibels 1/ int 1 / chat vector .

Sorry for the english and if you can i would realy apreciate the help.

CodePudding user response:

The problem is that the %s scanf format specifier will only match a single word of input. Therefore, instead of matching John of Sea, it will only match John and leave of Sea on the input stream.

If you want to read all characters up to (but not including) the comma, then you should use %[^,] instead of %s.

Also, you should always check the return value of scanf to verify that it was able to match all 3 arguments, before attempting to use these arguments.

Additionally, I recommend to limit the number of characters written to Name, so that if the input is too large to fit into Name, no buffer overflow will occur (which may cause your program to crash). Since Name has a size of 100 characters, it has room for 99 normal characters plus the terminating null character. Therefore, I recommend to limit the number of matched characters to 99, by using

  • Related