【问题标题】:Read strings from a file [closed]从文件中读取字符串[关闭]
【发布时间】:2016-08-17 20:56:03
【问题描述】:
 FILE *fp;
char name[50];
fp=fopen("stu.txt","r");
while(fgets(name,50,fp)!=NULL)
{

    printf(" %s",name);
    fgets(name,50,fp);

}
fclose(fp);

在我的文件中,4 个不同的行中有 4 个名称,但输出只显示第一个和第三个名称。有什么问题?我知道这是非常基本的,但这占用了我很多时间。

【问题讨论】:

  • 删除第二个fgets(name,50,fp);
  • while 循环条件没有指定任何会导致循环在主体内发生时终止的条件——它是在每个(潜在的)循环传递之前实际评估的表达式以决定是否执行循环体(如果结果非零则发生)。将fgets() 放入循环条件中将在每个循环通过之前检查条件时调用它......并且循环体内的fgets() 独立于它(您的循环仅在条件中的fgets() 调用时结束返回NULL,但不是循环体中的那个)。

标签: c string io


【解决方案1】:

您正在 (f) 进入循环块内的while 语句,因此您正在推进文件位置,而无需利用您在内部调用中读取的内容。试试这个:

while(fgets(name,50,fp)!=NULL)
{
  printf(" %s",name);
}

【讨论】:

    【解决方案2】:

    从循环体中删除fgetswhile 表达式中的 fgets 已经完成了这项工作。

    【讨论】:

      【解决方案3】:
      #include <stdio.h>
      
      int main ()
      {
      
         FILE *fp;
         int c;
      
         fp = fopen("file.txt","r");
         while(1)
         {
            c = fgetc(fp);
            if( feof(fp) )
            {
               break;
            }
            printf("%c", c);
         }
         fclose(fp);
         return(0);
         }
      

      【讨论】:

      • OP 的代码是基于行的。你的是基于字符的。
      • #include #include #include using namespace std; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv);字符串 sLine = ""; ifstream 文件; infile.open("temp.txt"); while (!infile.eof()) { getline(infile, sLine); cout
      • OP 的代码是 C(并且问题标记为 C)。您评论中的代码是 C++。最后一行打印两次。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 2019-05-23
      相关资源
      最近更新 更多