简体   繁体   English

使用fscanf从文件中读取格式化的字符串

[英]Using fscanf for reading formatted string from file

I have a file with contents as shown below. 我有一个内容如下的文件。

[John][Antony][Mathew] Australia

I need to use fscanf to read contents from file. 我需要使用fscanf从文件中读取内容。

Output should be: 输出应为:

firstName = John
middleName = Antony
lastName = Mathew
Country = Australia

What is the format to be used in fscanf to get firstName, middleName, lastName and country in separate strings? fscanf使用哪种格式来在单独的字符串中获取firstName,middleName,lastName和country?

Currently fscanf(fp, "[%[^]]",firstName) gives firstName correctly. 当前fscanf(fp, "[%[^]]",firstName)正确给出了firstName。

Akin to @BLUEPIXY comment "[%[^]]][%[^]]][%[^]]] %[^\\n]%*c" . 类似于@BLUEPIXY注释"[%[^]]][%[^]]][%[^]]] %[^\\n]%*c"

Since data is certainly per line , read a line first and then parse it. 由于数据肯定是每行 ,因此请先读取一行然后解析。

The format needed is "[%99[^]]]" which says to 1) scan '[' 2) scan up to 99 non- ] char and form a string 3) scan ']' . 所需要的格式是"[%99[^]]]"其表示为1)扫描'[' 2)扫描多达99非]炭和形成串3)扫描']'

#define N 100
#define FMT "[%99[^]]]" 
#define FMTCTY " %99[^\n]" 
char firstName[N], middleName[N], lastName[N], Country[N];

char buf[4*N + 10];
while (fgets(buf, sizeof buf, fp) != NULL) {
  if (4 != sscanf(buf, FMT FMT FMT FMTCTY, firstName, middleName, lastName, Country)) {
    break;
  }
  foo(firstName, middleName, lastName, Country);
}

Confident OP can form the needed output format string. 置信的OP可以形成所需的输出格式字符串。

char buf[1024];

FILE* fp = fopen("file.in", "r");
fgets(buf, sizeof(buf), fp);
fclose(fp);

// substitute '[' and ']' with a space

sscanf(buf, "%s%s%s%s", firstName, middleName, lastName, Country);

Also can be done by reading character stream and overpass all spaces, '[' and ']'. 也可以通过读取字符流并越过所有空格'['和']'来完成。

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

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