如何纠正这个程序? (编者)

时间:2014-02-12 08:43:43

标签: c++

(我刚刚编辑了我的帖子,对不起有困惑)你能帮我解决这个问题吗?我期待一系列的答案位置。     // 2-12-14.cpp:定义控制台应用程序的入口点。     //

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {
    int x = 0;
    char answer[25];
    for (x = 0; x < 25; x++) {
        do {
            cout << x + 1 << ".";
            scanf("%c", answer + x);
        } while (
            (answer[x] != 'A')
            && (answer[x] != 'B')
            && (answer[x] != 'C')
            && (answer[x] != 'D')
        );  
    }

    system("PAUSE");
    return 0;
}

为什么第二个输出会给出双数?

scanf("%c", answer + x);

当我用以下代替时:

cin>>answer[x]; //this was previously cout<<answer[x] **sorry for the confusion**

......工作正常。

1 个答案:

答案 0 :(得分:1)

  

为什么第二个输出会给出双数?

因为你提供双重输入。如果您输入“A&lt; enter&gt;”然后第一个字符是A,第二个字符是输入。这会导致您的循环输出然后重复,从而产生两个输出。

由于您的代码期望在输入之间输入,因此您不应该输入一个。在同一行输入所有答案,代码将正常工作。或者,将代码更改为静默忽略行结束字符。