C ++ fstream构建但没有运行

时间:2016-04-22 23:34:42

标签: c++

我正在为我的班级构建一个程序,要求我们从.txt文件导入数据,项目名称/价格将用于计算盐税和总计。我的老师把这个作为一个例子,但我不能让它运行。

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;

int main()
{ // Beginning of main function

string name;
ifstream data_in;
ofstream data_out;

int cnt=0;
int number;

struct Item
{
    int item_n;
    char disc[50];
    float price;
};

Item store[999];

data_in.open("cost.txt");
data_out.open("file_out.txt");

while(!data_in.eof())
{
    //cout << "Enter in the item number: ";
    data_in >> store[cnt].item_n;
    //cout << "Enter in the description for item number " << store[cnt].item_n << ": ";
    data_in >> store[cnt].disc;
    //cout << "Enter in the price for the " << store[cnt].disc << ": $";
    data_in >> store[cnt].price;
    cnt++;
}
cout << endl << endl;

number = cnt;
for (cnt=0; cnt<number; cnt++)
{
    name = store[cnt].disc;
    cout << setw(5) << store[cnt].item_n << "   " << store[cnt].disc << setw(16-name.length()) << "$" << setw(9) << store[cnt].price << endl;
}

for (cnt=0; cnt<number; cnt++)
{
    name = store[cnt].disc;
    data_out << setw(5) << store[cnt].item_n << "   " << store[cnt].disc << setw(16-name.length()) << "$" << setw(9) << store[cnt].price << endl;
}


return 0;
}

这是cost.txt文件中的信息

书籍45.01 钢笔21.03 铅笔10.90 帽子50.00 上限800.00 食物1.00

2 个答案:

答案 0 :(得分:0)

尝试以下更改,其余代码似乎有效:

data_in.open("cost.txt");
data_out.open("file_out.txt");
if (!data_in.is_open() || !data_out.is_open())  //Test if files opened correctly...
{
    cout << "Failed to open a file!\n";
    return 1;
}

float SalesTotal = 0;
while(true)
{
     if (!(data_in >> store[cnt].disc))  
     {
         //Failed to read first element in this record - could be eof or format error
         if (data_in.eof())
             break;         //eof - all records read.

         cout << "Format error first field\n";
         return 1;          //format error on first field.
     }

     if (!(data_in >> store[cnt].price))
     {
         cout << "Format error second field\n";
         return 2;          //format error on second field.
     }

     store[cnt].item_n = cnt + 1; //Item number is not a field in your file, use the counter...

     SalesTotal += store[cnt].price;
     cnt++;
}

if (!cnt)
{
    cout << "No records read\n";
    return 3;   //No valid records read.
}

float GrandTotal = ((SalesTotal / 100) * 6) + SalesTotal;
cout << "Sales total: " << SalesTotal << " Grand total:" << GrandTotal << "\n";

答案 1 :(得分:0)

您编写的代码为每个Item读取三件事:商品编号,说明和价格。

您显示的示例数据文件每个项目只包含两件事:看起来像是描述和价格。

预期的数据格式与输入文件的内容不匹配。这段代码永远不会有效。一个或另一个是错的。加上代码中的所有其他问题,如评论中所述。