简体   繁体   中英

Using “fscanf” in C How can Split two strings?

I want to a linked list in C using file operations. I want to get a line and split it and storage in structers. But I cant split two strings.

My File like this:

1#Emre#Dogan
2#John#Smith
3#Ashley#Thomas
etc...

I want to read one line from file using fscanf.

fscanf(file,"%d#%s#%s",&number,name,surmane);

But the result is

Number : 1
Name : Emre#Dogan

How can get rid of that # element in the name and split it to name and surname;

#include <stdio.h>
#include <string.h>

int main(void) {

    FILE *fptr;
    fptr = fopen("Input.txt", "r");

    int number;
    char *name;
    char *surname;
    char line_data[1024];

    fgets(line_data, 1024, fptr);

    number = atoi(strtok(line_data, "#"));
    name = strtok(NULL, "#");
    surname = strtok(NULL, "#");    

    printf("%d %s %s", number, name, surname);
}

Output:

1 Emre Dogan

EDIT: Coverted the variable "number" from string to integer.

It's better to read a full line using fgets() , then parsing that line. This is more robust, using fscanf() directly on the input stream can be confusing due to the way fscanf() skips whitespace.

So, you could do:

char line[1024];

if(fgets(line, sizeof line, file) != NULL)
{
  int age;
  char name[256], surname[256];

  if(sscanf(line, "%d#%255[^#]#%255s", &age, name, surname) == 3)
  {
    printf("it seems %s %s is %d years old\n", name, surname, age);
  }
}

This uses the %[] format specifier to avoid including the # separator in the parsed strings. I think this is cleaner than strtok() , which is a scary function best avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM