【问题标题】:Why does this code compile but not actuall work?为什么这段代码可以编译但实际上不起作用?
【发布时间】:2014-04-21 05:32:31
【问题描述】:

第 12 到 23 行运行。但是在添加 if 语句时实际上并没有运行。它确实编译并运行。它询问第一个 printf 语句,然后在我选择一个字符时终止。为什么会发生这种情况,我该如何解决。

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char ch, file_name[25];
   FILE *fp;
   printf("Enter [A] and select file or [X] to exit:"); // Prompt user to select file or exit
   scanf("%c",&ch);
   scanf("%c",&ch);

   if (ch=='A')
   {
       printf("Enter the file name\n"); // if user chooses 'A' this code should run
       gets(file_name);

       fp = fopen(file_name,"r"); // reading file

       if( fp == NULL )
       {
           perror("File not found.\n");
           exit(EXIT_FAILURE);
        }
        printf("Contents of %s are:\n", file_name);

        while( ( ch = fgetc(fp) ) != EOF )
            printf("%c",ch);
    }
    else if (ch=='X')
    {
        printf("Exiting program...");
        exit(0);
    }
}

【问题讨论】:

  • 为什么一个可编译的代码应该真正起作用?非语法错误代码并不意味着它没有逻辑错误

标签: c compilation


【解决方案1】:

因为你有两个电话给scanf..

在第一个中,您正在成功读取输入的“A”或“X”。 在下一次调用中,您将读取之前被压入同一变量ch 的换行符(\n)。所以它不满足任何if 子句,只是从程序中出来..

改为第二次调用临时变量..

char temp;
scanf("%c", &temp);

另外,fgets 优于 gets

【讨论】:

    【解决方案2】:

    我猜你没有正确读取文件,试试:

    char buff[255];  //define buffer to read lines
    
    while ( !feof(fp ) ){
             memset(buff, '\0', sizeof( buff) );
             fgets(buff, 255, (FILE*)fp);
             printf("%s", buff );
          }
    
    fclose(fp); //don't forget to close
    

    【讨论】:

      【解决方案3】:

      有一大类程序可以编译但不能正常运行。这就是区分语法错误和运行时/逻辑错误的原因。

      scanf("%c",&ch);
      scanf("%c",&ch);
      

      假设这是为了去掉换行符,但将它读入ch 是个坏主意,因为它应该保留第一个字符。

      如果是这种情况,只需将其读入一些垃圾变量,以便保留ch

      char ch, junk, file_name[25];
      :
      scanf("%c",&ch);
      scanf("%c",&junk);
      

      遗憾的是,这种方法可能存在许多其他问题。如果你想要一个像样的线路输入功能,你可以找一个here。这比使用本质上不安全的gets() 要好得多。

      具有缓冲区溢出检测与预防、输入行过长自动刷新、提示输出等功能。一旦你用它来获取输入行,你需要做的就是将它与你想要的进行比较,比如:

      if (strcmp (buff, "A") == 0)
          doSectionA();
      else
          if (strcmp (buff, "X") == 0)
              doSectionX();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-06
        • 2013-08-08
        • 1970-01-01
        相关资源
        最近更新 更多