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

How can I ask the user to enter an integer or char with one question?

提问人:Uzuki Z 提问时间:10/28/2023 更新时间:10/29/2023 访问量:50

问:

我正在为一个学校项目制作杂货店界面。首先,有一个菜单询问用户是要 S 购买还是 Q-quit,如果他们选择 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++ 数组函数 结构

评论

1赞 Scheff's Cat 10/28/2023
考虑到您打算询问如何询问数字或字母,这太多了......请查看如何编写一个最小的可重复示例
0赞 Scheff's Cat 10/28/2023
设置代码的方式是,在要求用户进行其他选择时,我只能接受整数那么,这可能是错误的方式。为什么不这样呢?
0赞 Richard Critten 10/28/2023
读取以 .查看字符串的内容并决定要执行的操作。std::string
1赞 Pete Becker 10/28/2023
用户不输入整数或字符;他们输入文本。由程序来确定是否可以将文本转换为所需的类型。流提取器 () 可以做到这一点,每种不同类型的提取器都不同。如果要根据输入文本转换为不同的类型,则必须阅读文本并自己弄清楚。>>

答:

0赞 amagicman123456 10/29/2023 #1

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