Search code examples
cgetlinescanf

How should I use sscanf() to break the line into fields?


How to use sscanf() to separate input? here I have a getline to find input. I checked that input before and it is correct, which means it can read one line you input if you don't end the file. Then I was trying to separate what you input by using sscanf();.

  • First field is a char array with no length limit
  • The second field is a char array with length limit
  • The third field is a integer

What I want is if I input, for example:

bd_21 abs 124 32152 23415

Then it will print out bd_21 abs 124 because I only sscanf the first three elements and put them into the fields I specify. But when I run this, it shows

segmentation fault: 11.

I don't know what is wrong here. Can anyone explain how to use sscanf to break lines?

My Code:

int main() {
    char *input = NULL;
    size_t len = 0;
    char *field1 = NULL;
    char field2[33];
    int field3;
    while(getline(&input, &len, stdin) != EOF){
        //printf("%s", input);
        sscanf(input, "%s %32s %d", field1, field2, &field3);
        printf("%s %s %d\n", field1, field2, field3);
    }
    return 0;
}

Solution

  • It will crash. allocate memory for field1.

     char *field1 = NULL;