我的 C++ 程序不接受菜单后的输入

My C++ Program wont accept inputs after the menu

我在学校做一个class的程序,当我尝试运行我下面写的代码时(项目只完成了一半,但处于这样的状态它应该 运行 无论如何)菜单出现正常,但是它直接跳到程序的末尾并且不让我输入重要部分..

当我删除菜单时(稍后当我完成项目时这将是必需的)它工作正常,但是当我需要它时,它不会 运行 正确

//Project 4 Written By Nate

#include <iostream>
#include <iomanip>
using namespace std;

int menuOption;
char stockName[21],symbol[10];
float openingPrice,closingPrice,numberShares,gain;

int main()
{
    // MENU //
    cout<<"Welcome to Project 4! Please select the program you would like to run:\n\n 1)Stock Program\n\nEnter your selection: ";
    cin>>menuOption;
    if(menuOption == 1) {
        goto stockProgram;
    } else
    {
        cout<<"Invalid response received. Program will now terminate";
        return 0;
    }

    stockProgram:
    cout<<"This program will ask you information about a stock you own.\n\n";
    cout<<"Enter stock name: ";
    cin.get(stockName,21);
    cin.ignore(80,'\n');
    cout<<"Symbol: ";
    cin.get(symbol,10);
    cin.ignore(80,'\n');
    cout<<"Enter opening price: ";
    cin>>openingPrice;
    cout<<"Enter closing price: ";
    cin>>closingPrice;
    cout<<"Enter the number of shares: ";
    cin>>numberShares;
    cout<<"\n\n";
    gain=(numberShares*closingPrice)-(numberShares*openingPrice);
    cout<<setw(10)<<"Stock Name"<<setw(10)<<"Symbol"<<setw(10)<<"Opening"<<setw(10)<<"Closing"<<setw(10)<<"Shares"<<setw(11)<<"Gain\n";
    cout<<setw(10)<<stockName<<setw(10)<<symbol<<setw(10)<<openingPrice<<setw(10)<<closingPrice<<setw(10)<<numberShares<<setw(10)<<gain<<"\n\n";
    cout<<"=====================================================================\n";
    cout<<"  This gain could've been yours, too bad you are an anti-mac person.\n";
    return 0;
}

谢谢..

cin>>menuOption 之后添加 cin.ignore() - 这将读取当前驻留在缓冲区中的 int 并丢弃它,因为 EOF 是输入后的新行。

int main()
{
    // MENU //
    cout<<"Welcome to Project 4! Please select the program you would like to run:\n\n 1)Stock Program\n\nEnter your selection: ";
    cin>>menuOption; cin.ignore();
    if(menuOption != 1) {
        cout<<"Invalid response received. Program will now terminate";
        return 0;
    }
//etc
}

您可能在初始输入中的 1 之后还有一个换行符或其他字符。您在其他输入上使用了 cin.ignore 但不是第一个。

cout<<"Welcome to Project 4! Please select the program you would like to run:\n\n 1)Stock Program\n\nEnter your selection: ";
cin>>menuOption;
cin.ignore(80,'\n');

忽略将提取分隔符 \n

此外,每当处理 istream 时,检查它是否成功将输入转换为正确的类型:

#include <limits>
#include <sstream>

int myVariable;
if( (cin >> myVariable).fail() )
{
    // Error - input was not an integer
    std::cerr << "Input was not an integer" << std::endl;
    return -1;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');