开关盒后的过早输出

时间:2015-02-03 16:18:45

标签: c++ switch-statement case

业余问题....我的代码有一个逻辑门菜单供用户选择3门。然后程序查找头文件中的命名空间并返回该门的输出,我将其存储在out []中。门输出工作正常但我似乎无法在3个开关盒选择结束后打印它们。我尝试将它放入自己的函数中#34; void output()"但是在用户再选择2个门之前,程序仍会过早地打印输出。

输出y 1到3应该一起打印,但第一个打印在用户输入逻辑输入后立即打印

#include <iostream>
#include <iomanip>
#include "lab3.h"


using namespace std;
using namespace Gates;
void output( int o[]);


int menu(int, int);
int main()
{

    int a;
    cout << "Types of gates available:\n"
         << "1) AND\n"
         << "2) OR\n"
         << "3) NAND\n"
         << "4) NOR\n"
         << "5) XOR\n";


    for(int i=0; i<3; i++)
    {
    cout << "\nSelect gate #" << i+1 << " (1 to 5) => ";
    cin >> a;
    menu(a, i);
    }
}



int menu(int x, int j)
{

int out[3];
int a, b;
switch(x)
{
case 1:
    cout << "Enter two inputs for gate #" << j+1 << " (seperated by a space)      => ";
    cin >> a >> b;  // two inputs for gate
    out[j] = Gates::AND(a, b);   //store gate output in out1  (1 or 0)  
    break;

case 2:
    cout << "Enter two inputs for gate #" << j+1 << " (seperated by a space) => ";
    cin >> a >> b;
    out[j] = Gates::OR(a, b);   
    break;  

case 3:
    cout << "Enter two inputs for gate #" << j+1 << " (seperated by a space) => ";
    cin >> a >> b;
    out[j] = Gates::NAND(a, b);
    break;

case 4:
    cout << "Enter two inputs for gate #" << j+1 << " (seperated by a space) => ";
    cin >> a >> b;
    out[j] = Gates::NOR(a, b);
    break;

case 5:
    cout << "Enter two inputs for gate #" << j+1 << " (seperated by a space) => ";
    cin >> a >> b;
    out[j] = Gates::XOR(a, b);
    break;  
}

output(out);

return 0;
}

void output( int o[])
{
    cout << "\nOutputs => " << endl;
    for(int i=0; i < 3; i++)
    {
        cout << setw(10) << "\ny"<< i+1 << " = " << o[i];
    }
}

2 个答案:

答案 0 :(得分:2)

我认为问题可能是因为你在output函数中调用menu,而你可能打算从main函数调用它,可能是在for循环之后

答案 1 :(得分:0)

存储用户输入并在用户输入后调用菜单功能

int a[3];
int out[3];
for(int i=0; i<3; i++)
{
cout << "\nSelect gate #" << i+1 << " (1 to 5) => ";
cin >> a[i];
menu(a[i],out i);
}
output(out);

我强烈建议您使用调试器或在代码中放置printf来开始研究自己的代码流。