【问题标题】:scan a line with numbers and words and just keep the words in c用数字和单词扫描一行,然后将单词保留在 c 中
【发布时间】:2019-04-14 13:23:56
【问题描述】:

我有一个列出专辑和歌曲的文本文件。 例如:
平克弗洛伊德:月球的黑暗面
0:01:30 - 跟我说话
0:02:43 - 呼吸
0:03:36 - 奔跑中
0:04:36 - 天空中的伟大演出

我正在使用 sscanf 来获取每首歌曲的持续时间。当我试图获取歌曲的名称时,我只是得到一个空白页。我怎样才能丢弃我不想要的所有其他字符。到目前为止,我使用这个:

int temp1,temp2,temp3;
char str[100];
char symbol[2]="-";

FILE *fp;
fp = fopen("albums.txt","r");

if (fp == NULL) {
    printf("Error: unable to open ‘albums.txt’Report error.in mode ’r’\n");
    exit(EXIT_FAILURE);
}  


while (fgets(str, 100, fp) != NULL)
{
    if(strstr(str,symbol))
    {  
        sscanf(str,"%d:%d:%d",&temp1,&temp2,&temp3);
        getHour(temp1,temp2,temp3);         //temp1:hours, temp2:minutes, temp3:seconds
    }
}  

fclose(fp);

【问题讨论】:

    标签: c file-io scanf text-files fgets


    【解决方案1】:

    测试sscanf()的返回值是否成功。使用"%*d" 扫描int,但不保存。使用"%[^\n]" 扫描并保存所有非'\n' 字符。

    代码可以使用“-”作为扫描的一部分。

    while (fgets(str, sizeof str, fp) != NULL) {
      char title[sizeof str];  // Wide enough for anything from `str`.
      if (sscanf(str, "%*d :%*d :%*d - %[^\n]", title) == 1) {
        // success
        printf("<%s>\n", title);
      }
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      相关资源
      最近更新 更多