简体   繁体   English

在C中使用“ fscanf”如何分割两个字符串?

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

I want to a linked list in C using file operations. 我想使用文件操作在C中创建一个链接列表。 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 1#埃姆雷#多甘
2#John#Smith 2##约翰·史密斯
3#Ashley#Thomas 3#阿什利#托马斯
etc... 等等...

I want to read one line from file using fscanf. 我想使用fscanf从文件中读取一行。

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

But the result is 但是结果是

Number : 1 1号
Name : Emre#Dogan 姓名: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. 最好使用fgets()读取整行,然后解析该行。 This is more robust, using fscanf() directly on the input stream can be confusing due to the way fscanf() skips whitespace. 这更加健壮,由于fscanf()跳过空格的方式,直接在输入流上使用fscanf()可能会造成混淆。

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. 我认为这比strtok()更干净,最好避免使用这种可怕的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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