如何要求用户通过一个问题输入整数或字符?

问题描述 投票:0回答:1

我正在为学校项目制作杂货店界面。首先有一个菜单询问用户是否要 S 购物或 Q 退出,如果他们选择 S,则会弹出一个显示产品的菜单,其中包含每磅的价格。然后用户可以通过输入数字 1-来选择产品7 然后选择他们想要多少磅该产品。我的问题是,在此之后我应该要求用户做出选择,选择可以是另一个产品,因此可以是 1-7 之间的数字,或者他们可以从新菜单中输入选项,即 T- 交易完成或 X- 取消交易。我设置代码的方式是,当要求用户进行其他选择时,我只能接受整数。我只编码了大约一个月,所以任何指导都会有很大帮助。

#include <iostream>             
#include <iomanip>
#include <string>
#include <ctime>
#include <cctype>               
#include <cstdlib>              
#include <fstream>               
#include <cmath>

using namespace std;

struct Transaction
{
    string item;
    float price;
    
    
    //derived variables
    float subTotal;
    float totalSales;
    
    
    
};

// Decleration of prototype 
void projectStart();
void projectEnd();
int getIntegerData(string);
float getFloatData(string);
char getCharData(string);
string getStringData(string);
void mainMenu();
void loadFile(int&, Transaction []);
void transactionShopping(int, Transaction[]);
void subMenu();
void performCalculation(int, Transaction[]);

int main()
{
    // Displays start of project 
    projectStart();
    cout << fixed <<setprecision(2);
    
    //declared variables
    Transaction myPurchase[25];
    int itemSize;
    itemSize = 0;
    
    loadFile(itemSize, myPurchase);
    
    transactionShopping(itemSize, myPurchase);
    performCalculation(itemSize, myPurchase);
    
    
    
    // Displays end of project
    projectEnd();
    
    return 0;
    
}// end of main
void performCalculation(int itemSize, Transaction myPurchase[])
{
    float salesTax = .0825;
    float subTotal = 0;
    
    for (int ctr = 0; ctr < itemSize; ctr++)
    {
        subTotal = subTotal + myPurchase[ctr].subTotal;
    }
}
void transactionShopping(int itemSize, Transaction myPurchase[])
{ // start of transactionShopping(int itemSize, Transaction myPurchase[])

    //declared variables
    string dashes(40, '-');
    char selection;
    int itemSelection;
    float itemWeight;
    float cost;

    mainMenu();
    selection = getCharData("\tMake your selection: ");
    while(true)
    { // start of while(true)

        if (selection == 'X')
        {   
            cout << "!!! Transaction Cancelled" << endl;
            break;
        }
        else
        {   if (selection == 'S')
            {//start of if (selection == 'S')   
                cout << dashes << endl;
                cout << "\tHernandez Grocery Store" << endl;
                cout << dashes << endl;
                cout << "Shopping" << endl;
                for (int ctr = 0; ctr < itemSize; ctr++ )
                { //start of for loop
                    cout << ctr + 1 << " "<< myPurchase[ctr].item << " " << myPurchase[ctr].price << endl;
                } //end of for loop
                subMenu();
                itemSelection = getIntegerData("\tMake your selection: ");
    
                
                if (itemSelection >= 1 && itemSelection <= itemSize)
                { //start of if loop
                    itemWeight = getFloatData("\tEnter pounds of " + myPurchase[itemSelection -1].item + ": ");
                    
                    if (itemWeight > 0)
                    { //start of itemweight loop
                        cost = itemWeight * myPurchase[itemSelection -1].price;
                        cout << "\tCost: " << itemWeight << " lbs" << " of " << myPurchase[itemSelection -1].item << ": $" << cost << endl;
                    } // end of itemweight loop
                    else
                    { //start of else
                        cout << "ERROR Message. Enter a valid weight" << endl;
                    } //end of else
            }
            else if (selection == 'T')  
            {
                cout << "Grocery List" << endl;
                cout << "myPurchase[itemSelection -1].item" << endl;
            }
            }
        
        }
        
    }
} // end of transactionShopping(int itemSize, Transaction myPurchase[])


// menu function
void subMenu()
{ //start of subMenu
    string dashes(40, '-');
    cout << dashes << endl;
    cout << "T Complete Transaction" << endl;
    cout << "X Cancel Transaction" << endl;
    
    
} //end of subMenu
void mainMenu()
{ //start of mainMenu
    string dashes(40, '-');
    cout << dashes << endl;
    cout << "Hernandez Grocery store" << endl;
    cout << dashes << endl;
    cout << "Main Menu" << endl;
    cout << "\tS Shop" << endl;
    cout << "\tQ Quit" << endl;
    cout << dashes << endl;
} //end of mainMenu
//function will load the file
void loadFile(int & itemSize, Transaction myPurchase[])
{ //start of void loadFile(int & itemSize, Transaction myPurchase[])
    ifstream menuFile("menu.txt");
    string item;
    float price;
    itemSize = 0;
    
    if (menuFile)
    { //if (menuFile)
        while (menuFile >> item >> price)
        { // start of while (menuFile >> item >> price)
            
            myPurchase[itemSize].item = item;
            myPurchase[itemSize].price = price;
            itemSize = itemSize + 1;

            
            if (itemSize == 25)
            { 
                break;
            } 
        } //while while (menuFile >> item >> price)
    menuFile.close();
    }// if (menuFile)
    else
    {
        cout << "File does not exist" << endl;
        
    }

} //end of void loadFile(int & itemSize, Transaction myPurchase[])

char getCharData(string prompt)
{ //start of getCharData
    char value;
    while (true)
    { //start of while(true)
            cout << prompt;
            cin >> value;
            
            cin.clear(); //clears the cin
            cin.ignore(120, '\n'); //clears up to 120 characters or until enter button is hit
            
    
            value = toupper(value);
            if (value == 'S' || value == 'Q' || value == 'T' || value =='X')
            {
                return value;
            }
        cout << "\t\tError Message Invalid Selection" << endl;
    }
} //end of getCharData

// This function will get a float value from the user
float getFloatData(string prompt)
{
    float value;
    
    while (true)
    {
        cout << prompt;
        while (!(cin >> value))
        {
            cout << "\t\tError Message. Non numeric is entered"  << endl;
            cin.clear(); 
            cin.ignore(120, '\n');  
            cout << prompt;
        } 
            
        if (value >= 1 && value <= 10)
        {
            return value;   
        } 
            
        cout << "\t\tError Message. ONLY integers between 1 and 10"  << endl;
    } 
} 

// This function will get an integer value from the user
int getIntegerData(string prompt)
{
    int value;
    
    while (true)
    {
        cout << prompt;
        while (!(cin >> value))
        {
            cout << "\t\t\tError Message. Non numeric is entered"  << endl;
            cin.clear(); // clear error buffer
            cin.ignore(120, '\n');  // c;lear upto 120 chars or it reaches an enter
            cout << prompt;
        } //    while (!(cin >> value))
        if (value >= 1 && value <= 7)
        {
            return value;
        }
        cout << "Enter from provided options 1-7" << endl;
        
            
    } // end of while (true)
} // end of int getIntegerData()

// This function will return a string data entered by users
string getStringData(string prompt)
{
    string value;
    cout << prompt;
    getline(cin, value, '\n'); // accepts spaces in the entry
    
    return value;
    
} // end of int getStringData(string prompt)

// The function will display the start of the project 
void projectStart()
{
    cout << "-----------------------------"  << endl;
    cout << "Project " << endl;

    cout << "Objectives" << endl;
    cout << "\tUser can nagivate our product list and pick the product and amount they would like" << endl;
    cout << "\tThe user will receive a total price at the end or exit if they choose to cancel " << endl;
    cout << "-----------------------------"  << endl;
} // end of projectStart()

// The function will display the end of the project 
void projectEnd()
{
    cout << "-----------------------------"  << endl;
    cout << "End of Project" << endl;
    cout << "-----------------------------"  << endl;
} // end of projectEnd()```



I tried replacing my itemSelection = getIntegerData("\tMake your selection: "); with getCharData but not sure if this can even work since i would have to change my getchardata function to check for integers would entering them as '1' work?
c++ arrays function structure
1个回答
0
投票

您可以读入一个字符,即。

char input; std::cin >> input
。如果字符是数字
input >= '0' && input <= '9'
,则可以将其解析为整数
input - '0'
,否则可以将其解析为字符。

© www.soinside.com 2019 - 2024. All rights reserved.