【问题标题】:How to validate .txt data from an input file? c++如何验证输入文件中的 .txt 数据? C++
【发布时间】:2017-04-25 17:32:04
【问题描述】:

目标是从 .txt 中获取项目名称 - 字符串 - (.txt) 和价格 - 双倍 - (.txt)。我需要检查这个输入并确保它是有效的,如果不是,返回 1 并退出程序。我能够检查以确保输入文件已打开。但我对如何检查其他数据持空白。 验证被解释为一次以两个(项目/价格)为一组进行。

对于字符串值,我只需要确保该行不为空。对于双精度值,我需要确保它们是数字。

int getData(int& listSize, menuItemType*& menuList, int*& orderList)
{
    //-----Declare inFile
    ifstream inFile;
    string   price, size;

    //-----Open inFile
    inFile.open("Ch9_Ex5Data.txt");

    //-----Check inFile
    if (inFile.is_open())
    {
        //-----Get Amount of Items, Convert to int 
        getline(inFile, size);
        listSize = stoi(size);      <---This needs to be positive int 

        //-----Set Array Size
        menuList  = new menuItemType[listSize];
        orderList = new int[listSize];

        //-----Get Menu
        for (int x = 0; x < listSize; x++)
        {
            //-----Get menuItem
            getline(inFile, menuList[x].menuItem);//-make sure data recieved

            //-----Get menuPrice convert to double
            getline(inFile, price);
            menuList[x].menuPrice = stod(price);//make sure double < 99

            orderList[x] = 0;
        }                      //teacher explained i should validate in 
                                 groups of two
        return 0;
    }
    else
    {
        return 1;
    }
}

//This is the .txt.
8
Plain Egg
1.45
Bacon and Egg
2.45
Muffin
0.99
French Toast
1.99
Fruit Basket
2.49
Cereal
0.69
Coffee
0.50
Tea
0.75

【问题讨论】:

  • 示例:if (listSize &lt; 0) return 1; 不过,强烈建议返回一个布尔值。更容易推断出意图。调用函数来读取文件。调用返回错误。嗯。文件可能未读取。返回一个数字本质上是没有意义的。是阅读的项目数吗?是错误代码吗?这是 Deep Thought 一直在等待的问题吗?
  • 还建议在调用getline 之后测试流状态,以便您知道读取是成功还是失败。

标签: c++ validation input io


【解决方案1】:

例如,您可以创建一个函数,告诉您一对值是否有效(当menu != empty0 &lt; price &lt; 99时。每次读取每对值时都会调用此函数。

bool validation(const string& menu, const double& price){ 
    if(menu.empty() || price < 0 || price > 99)
        return 1 ;
    else
        return 0 ;
}

当配对正确时,此函数返回 0,否则返回 1(如您所指出的)。

现在只需要在每次创建新的值对时调用该函数即可。当其中一项无效时,将退出程序。

for (int x = 0; x < listSize ; x++)
{
    //-----Get menuItem
    getline(inFile, menuList[x].menuItem);//-make sure data recieved

    //-----Get menuPrice convert to double
    getline(inFile, price);//-make sure data recieved
    menuList[x].menuPrice = atof(price.c_str());//make sure double < 99

    //teacher explained i should validate in groups of two
    if(validation(menuList[x].menuItem, menuList[x].menuPrice))
        return 1 ;

    orderList[x] = 0;
}

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多