【发布时间】:2018-03-19 21:39:34
【问题描述】:
所以我有一个 .txt 文件,我应该从中读取信息并显示在一个整洁的小表格中。这是 .txt 文件内容的 sn-p 格式
农场名称、商品数量、商品、价格、总价
Collins Farm, 43900 tomatoes 0.67 29413
Bart Smith Farms, 34910 cassavas 0.99 34560.9
Allen Farms, 117 coconuts 0.54 63.18
等等……
它应该在控制台中打印为
柯林斯农场(此处有一些空间)43900 件商品共贡献了 29413.00 美元
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int addLine(int);
int main()
{
using std::ifstream;
ifstream myFile;
myFile.open("ASSGN6-B.txt");
string farmName;
int itemCount;
string itemName;
double itemPrice;
double totalPrice;
if (!myFile)
{
cout << "File open failed!" << endl;
}
else
{
cout << "\t\t\t=========================================================" << endl;
cout << "\t\t\t= FARMER'S MARKET INVENTORY =" << endl;
cout << "\t\t\t=========================================================" << endl;
while (myFile.good())
{
getline (myFile, farmName);
getline (myFile, itemName);
myFile >> itemName >> itemPrice >> totalPrice;
cout << farmName << " " << itemCount << " items contributed totaling $" << totalPrice << endl;
}
}
myFile.close();
return 0;
}
这就是我一直在搞砸的,试图弄清楚这个输入的东西是如何工作的。我想我真正不明白的是它应该如何知道哪个项目是哪个。我以前认为它只是一次读取一行,但必须有一种方法可以将同一行中的项目分开并在控制台中单独打印。
此外,一些农场名称在 .txt 文件中出现两次,如果重复,我应该将它们的数据合并到一行中。对此的帮助也将不胜感激。
谢谢。
【问题讨论】:
-
我强烈建议在互联网上搜索“StackOverflow C++ 读取文件 csv”。这将列出许多示例供您学习。