【问题标题】:read and jump lines from a file C [closed]从文件 C 中读取和跳转行 [关闭]
【发布时间】:2016-04-06 17:20:50
【问题描述】:
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
  FILE* file = fopen("questions-words.txt", "r"); 
  char line[256];

  while (fgets(line, sizeof(line), file) != NULL) {                
    if (line[0]==":") {
      continue;
    }
    printf("%s", line);   
  }
  fclose(file);
  return 0;
}

您好,我试图打印文件的行并跳转以“:”开头的行,但它似乎不起作用。 我也无法打印 line[0] 它会发出警告,因为“line is type int”

【问题讨论】:

  • 代码不应该编译if (line[0]==":"){(或者,至少应该产生警告)。您不能将字符与字符串进行比较;请改用':'。注意编译器警告——编译器对 C 的了解比你多得多,如果它发出警告,你应该假设它是正确的,并且应该修复你的代码,这样它就不会警告你。 (在使用file 之前,您还应该检查fopen() 是否成功;如果无法打开文件,您的程序可能会崩溃。...在user1320881 添加相同评论时添加。)
  • 也总是测试打开文件是否成功。
  • 非常感谢。我只是想尽可能地发布最简化的代码,但也感谢您提供的提示

标签: c string buffer stdio


【解决方案1】:

而不是这个 -

if (line[0]==":"){

使用这个 -

if (line[0]==':'){   // note the single quotes

注意 - ';'int 类型(正如 Cool Guy 所指出的),不像 ":" 是字符串文字。

【讨论】:

  • ':' 的类型是 int,而不是 char
  • @CoolGuy 更正它的字符文字,我的错。
【解决方案2】:
    #include <stdio.h>
    #include <string.h>


    int main(int argc, char* argv[])
    {


        FILE* file = fopen("questions-words.txt", "r"); /* should check the result */
        if (file==NULL){
            return-1;
        }
        char line[256];
        char first[20],second[20],third[20],fourth[20],temp[20];


        while (! feof(file)) {
            fscanf(file,"%s \t", first);
            if (!strcmp(first,":")){
                fscanf(file,"%s \t",temp);
            continue;
                }

                fscanf(file,"%s \t", second);
                fscanf(file,"%s \t", third);
                fscanf(file,"%s \t", fourth);
                printf("%s %s %s %s \n", first, second, third, fourth);



        }
                fclose(file);

                return 0;
    }

@ameyCu 的答案更好,但因为我知道每行有 4 个单词,所以我也找到了这个解决方案(以防万一对某些人有帮助)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2016-06-17
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多