如何扫描字数未知的字符串?

问题描述 投票:1回答:1

我有一个这样的文本文件:

代码主题名称等

其中codeects是整数,而subject_name是一个字符串,可以是多个单词长,有时还包含数字。

我尝试过fscanf(f, "%d %s %d", &code, subject_name, &ects);,该操作不起作用,因为字符串中有空格。

"%d %[^\n] %d"也将不起作用,因为字符串会吞下ects

正确的方法是什么?

c scanf
1个回答
0
投票

步骤1:读取

#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);
  }
  ...

确定,现在我们已读取line并另存为string

步骤2:由于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

现在buf希望可以用用户代码codesubject_name等进行解析的sscanf()strtol()。将其留给OP。

© www.soinside.com 2019 - 2024. All rights reserved.