简体   繁体   English

如何 fscanf 字数未知的字符串?

[英]How to fscanf string with unknown number of words?

I have a text file formatted like this:我有一个格式如下的文本文件:

code subject_name ects代码subject_name ects

Where code and ects are integers, and subject_name is a string that can be multiple words long and sometimes contains a number.其中codeects是整数,而subject_name是一个字符串,可以是多个单词长,有时包含一个数字。

I've tried fscanf(f, "%d %s %d", &code, subject_name, &ects);我试过fscanf(f, "%d %s %d", &code, subject_name, &ects); which doesn't work because there are spaces in the string.这不起作用,因为字符串中有空格。

"%d %[^\\n] %d" also won't work because the string swallows up ects . "%d %[^\\n] %d"也不起作用,因为字符串会吞掉 ects

What would be the correct way to do this?这样做的正确方法是什么?

Step 1: read a line第一步:读一行

#define LINE_MAX_EXPECTED_SIZE 100
char buf[LINE_MAX_EXPECTED_SIZE + 2];// Let code read lines that are too long

if (fgets(buf, sizeof buf, f)) {
  buf[strcspn(buf, "\n\r")] = '\0';  // lop off potential end-of-line
  if (strlen(buf) >= LINE_MAX_EXPECTED_SIZE || buf[0] == '\0') {
    fprintf(stderr, "Line too long/short. <%s>\n", buf); 
    exit(EXIT_FAILURE);
  }
  ...

OK, now we have the line read and saved as a string .好的,现在我们读取了该并将其保存为string

Step 2: Since subject_name and ects can be a number, let code look for ects first since it is one and only one number.第二步:由于subject_nameects可以是一个数字,所以让代码先寻找ects因为它是一个并且只有一个数字。

  // Start at end
  char *end = strlen(buf) - 1;
  if (!isdigit((unsigned char) *end)) {
    fprintf(stderr, "No number at end. <%s>\n", buf); 
    exit(EXIT_FAILURE);
  }
  while (end > buf && isdigit((unsigned char) * --end)) {
    ;
  }
  if (end > buf && (*end == '-' || *end == '+')) {
    end--;
  }
  ects = atoi(end + 1); // or better strtol()
  end[1] = '\0'; // lop off ects

Now buf has, hopefully, code and subject_name which can be parsed with user code, sscanf() , strtol() , etc. Leave that for OP.现在buf有希望, codesubject_name可以用用户代码解析, sscanf()strtol()等。把它留给 OP。

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

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