【发布时间】:2009-07-24 16:30:46
【问题描述】:
C++ Primer Plus 中的一个练习是让我使用 fstream 打开一个 txt 文件并将数据输入到结构中然后输出。 txt 文件的第一行是“捐助者”的数量。我似乎遇到的问题是(我认为)当我使用“inFile >> value;”时检索数字然后通过new分配结构,它需要一个int并得到一个字符串?它是否正确?我应该做些什么不同的事情?
//ch6 p278 exercise #9
#include <iostream>
#include <cstring>
#include <fstream>
#include <cstdlib>
using namespace std;
const int SIZE = 60;
struct contributions
{
char name[20];
double dollars;
};
char filename[20];
string donors;
bool donated;
int main()
{
char filename[SIZE];
cout << "Enter name of file to scan: ";
cin >> filename;
fstream inFile;
inFile.open(filename);
if(!inFile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
inFile >> donors;
contributions * ptr = new contributions[donors];
for(int h = 0; h < donors; h++)
{
inFile >> ptr[h].name);
inFile >> ptr[h].dollars);
}
//BEGIN OUTPUT OF STRUCTURES
cout << "GRAND PATRONS:\n";
for(int i = 0; i < donors; i++)
{
if(ptr[i].dollars >= 10000)
{
cout << ptr[i].name << " donated " << ptr[i].dollars << endl;
donated = true;
}
}
if (!donated) {cout << "none.\n";}
donated = false;
cout << "PATRONS:\n";
for(int i=0; i < donors; i++)
{
if(ptr[i].dollars < 10000)
{
cout << ptr[i].name << " donated " << ptr[i].dollars << endl;
donated = true;
}
}
if (!donated) {cout << "none.\n";}
delete ptr;
return 0;
}
【问题讨论】:
-
与手头的问题分开,因为你已经使用
new的数组版本来分配ptr,你将需要使用delete的数组版本,比如这个:delete[] ptr;
标签: c++