【发布时间】:2017-07-06 01:58:51
【问题描述】:
我在显示输出时遇到问题。总是有额外的行被打印。我做了一些研究,结果证明这是因为我的 getline。我也为格式道歉
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct menuItemType
{
string menuItem;
double menuPrice;
};
int main()
{
menuItemType plainEgg;
menuItemType baconEgg;
menuItemType muffin;
menuItemType frenchToast;
menuItemType fruitBasket;
menuItemType cereal;
menuItemType coffee;
menuItemType tea;
ifstream infile;
infile.open("Ch9_Ex5Data.txt");
while(infile)
{
getline(infile,plainEgg.menuItem);
infile >> plainEgg.menuPrice;
getline(infile,baconEgg.menuItem);
infile >> baconEgg.menuPrice;
getline(infile,muffin.menuItem);
infile >> muffin.menuPrice;
getline(infile,frenchToast.menuItem);
infile >> frenchToast.menuPrice;
getline(infile,fruitBasket.menuItem);
infile >> fruitBasket.menuPrice;
getline(infile,cereal.menuItem);
infile >> cereal.menuPrice;
getline(infile,coffee.menuItem);
infile >> coffee.menuPrice;
getline(infile,tea.menuItem);
infile >> tea.menuPrice;
cout << plainEgg.menuItem << plainEgg.menuPrice << endl;
cout << baconEgg.menuItem << baconEgg.menuPrice << endl;
cout << muffin.menuItem << muffin.menuPrice << endl;
cout << frenchToast.menuItem << frenchToast.menuPrice << endl;
cout << fruitBasket.menuItem << fruitBasket.menuPrice << endl;
cout << cereal.menuItem << cereal.menuPrice << endl;
cout << coffee.menuItem << coffee.menuPrice << endl;
cout << tea.menuItem << tea.menuPrice << endl;
}
infile.close();
return 0;
}
文件内容
Plain Eggs
1.45
Bacon and Eggs
2.45
etc.
我尝试过使用
if (infile.eof())
cout << endl;
这是我的输出
Plain Egg1.45 // <-- this is the only correct output
Bacon
and Egg2.45
Muffin
0.99
French
Toast1.99
Fruit
Basket2.49
Cereal
0.69
Coffee
0.50
Tea
0.75
唯一正确打印的是第一行。 (注)我必须使用结构。
【问题讨论】:
-
在阅读时测试错误,而不是在阅读 16 次之前测试一次,因为所有错误都可能失败。您在混合 getline 和
>>时也会遇到一些麻烦,而不会忽略掉剩余的换行符。由于您的价格是一个字符串,您不妨阅读整行并简化您的生活。你也可以考虑一个数组。 -
你不能在 getline 之后使用 eof() ,因为那是文件的结尾。您可能应该检查 EOL 或在 getline() 中使用 \n 作为分隔符并使用 get line() 而不是 >>
-
这是一些关于混合
getline和>>的好读物。 stackoverflow.com/questions/21567291/… -
@RetiredNinja 感谢您的帮助,我会阅读更多内容。
-
@SurajS 我将更新我的代码并再次发布。谢谢