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

时间:2017-03-16 17:01:18

标签: c++ iomanip

我正在为学校的一个班级做一个程序,当我尝试运行我在下面写的代码时(只有一半的项目完成了,但它处于一个应该运行的状态)菜单出现很好,但然后它直接跳到程序的末尾,不会让我输入重要的部分..

当我删除菜单时(这在我完成项目之后将是必需的)它可以正常工作,但是当它需要它时,它就不能正常运行

//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;
}

谢谢..

2 个答案:

答案 0 :(得分:2)

您可能在初始输入中的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');

ignore将提取分隔\ 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');

答案 1 :(得分:1)

cin>>menuOption之后添加cin.ignore() - 这将读取当前位于缓冲区内的int&amp; {丢弃它,因为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
}