You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取含缺失数据的TXT文件行并正常打印?C语言问题排查

问题:读取含缺失数据的TXT文件时程序提前终止

问题描述

尝试读取TXT文件中的患者数据并打印到终端,但程序并未打印所有行,在遇到第一行含缺失数据的行(1048|Banjo Codi|TBD|)后就停止了。移除缺失数据行和代码中的else/if判断后,程序运行正常,推测是缺失数据导致的问题。

患者数据文件内容

1024|Shaggy Yanson|CELL|3048005191
1032|Pugsley Yanson|CELL|3048005191
1040|Beans Maulin|HOME|3649155831
1048|Banjo Codi|TBD|
1056|Lettuce Peas|WORK|7934346809
1064|Bullet Lemme|TBD|
1072|Nugget Smee|WORK|3886893085
1080|Bessie Lidgely|TBD|
1088|Potato Yards|HOME|5836788577

问题代码

#include <stdio.h>
#include <string.h>
int importPatients();

int main()
{
  importPatients();
  return 0;
}

int importPatients()
{
  FILE *fp = NULL;

  int patientNum;
  char firstName[31], lastName[31], phoneType[5], phone[11];

  fp = fopen("patientData.txt", "r+");

  if (fp != NULL)
  {
    while (!feof(fp))

    {
      if (fscanf(fp, "%d|%s %31[^|]|%5[^|]|%s", &patientNum, firstName, lastName, phoneType, phone) == 5)
      {
        printf("%d | %s %s | %s | %s\n", patientNum, firstName, lastName, phoneType, phone);
      }

      else if (fscanf(fp, "%d|%s %31[^|]|%4[^|]|", &patientNum, firstName, lastName, phoneType))
      {
        printf("%d | %s %s | %s |\n", patientNum, firstName, lastName, phoneType);
      }
    }
    fclose(fp);
  }
  return 0;
}

补充说明

  • 这是C语言入门课程的作业,除string.h外不能使用其他特殊库。
  • 更新:改用fgets和sscanf后,程序运行正常!

内容的提问来源于stack exchange,提问作者chickpea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:32:05