【发布时间】: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 < 0) return 1;不过,强烈建议返回一个布尔值。更容易推断出意图。调用函数来读取文件。调用返回错误。嗯。文件可能未读取。返回一个数字本质上是没有意义的。是阅读的项目数吗?是错误代码吗?这是 Deep Thought 一直在等待的问题吗? -
还建议在调用
getline之后测试流状态,以便您知道读取是成功还是失败。
标签: c++ validation input io