【问题标题】:Scanf causes C program to crashScanf 导致 C 程序崩溃
【发布时间】:2012-01-07 00:56:23
【问题描述】:

这个简单的问题导致我的整个程序在第一次输入时崩溃。如果我删除输入,程序可以正常工作,但是一旦我将 scanf 添加到代码中并输入输入,程序就会崩溃。

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

#define MAXEMPS 3


// stub program code
int main (void){
    char answer;

    do
    {

        printf("\n Do you have another(Y/N): ");
        scanf("%c", answer);
    }while(answer == 'Y' || answer == 'y');

    getchar();
    printf("  Press any key ... ");
    return 0;
} // main

【问题讨论】:

  • fflush(stdin)(或任何其他输入了最后一个操作的流)未由标准定义。如果您使用的是 Windows,则操作定义明确……但如果您的代码将在任何其他操作系统上编译,您将遇到一个您现在可以避免的错误。不要fflush(stdin)!
  • 感谢您提供有关 fflush 的信息,我的教授让我们使用它。
  • 嗯……等效的标准成语是int flushstdin(void) { int ch; while (((ch = getchar()) != '\n') &amp;&amp; (ch != EOF)) /* void */; return ch == EOF ? EOF : 0; }。与教授交谈并改用它

标签: c crash scanf


【解决方案1】:

你必须将变量的地址传递给scanf:

 scanf("%c", &answer);

【讨论】:

    【解决方案2】:

    使用“&answer”。并摆脱多余的“fflush()”命令...

    更好,替换为“answer = getchar()”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多