问下:大家是如何读取文件中输入的下一行的?
这是我的程序,作用是从文本中读取第一行确定循环次数,之后循环读入每一行的数据(其中每两行为一组):#include<iostream>
#include<fstream>
#include<cstdlib>
const int SIZE=60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream inFile;
cout << "Enter name of data file:";
cin.getline(filename,SIZE);
inFile.open(filename);
if(!inFile.is_open())
{
cout << "Could not open the file " << filename<<endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
struct person
{
string name;
double donation;
};
int people;
inFile >> people;
person * person_p = new person[people];
int i;
string temp;
for(i = 0;i < people;i++)
{
getline(inFile,temp);
getline(inFile,person_p[i].name);
inFile >> person_p[i].donation;
}
cout << "\n\n\nGrand Patrons\n\n";
int number_1 = 0;
for(i = 0;i < people;i++)
{
if(person_p[i].donation >= 10000)
{
cout << person_p[i].name<<"\t\t\t" << person_p[i].donation << endl;
number_1++;
}
if( (0 == number_1) && (people-1 == i) )
cout << "none\n";
}
cout << "\n\n\nPatrons\n\n";
int number_2=0;
for(i = 0;i < people;i++)
{
if(person_p[i].donation < 10000)
{
cout << person_p[i].name << "\t\t\t" << person_p[i].donation << endl;
number_2++;
}
if( (0 == number_2) && (people-1 == i) )
cout << "none\n";
}
system("pause");
return 0;
}
文件abc.txt中的内容为:
3
BBGASJ
50000
Bill Gates
88888
ARAGAKI YUI
5000
有两点疑惑:
1,之前输入循环中没加getline(inFile,temp);导致输出string全为空,double全为0,但按getline(inFile,person_p[i].name);每次也是读取一行,即第一次把空行当作string读入,第二次本应读取double,但遇到第二行的B,导致类型不匹配,输入流关闭。可为什么之后两组输出也为空和0?
2,想请问大家是如何控制换行读取的?
[[it] 本帖最后由 BBGASJ 于 2008-9-20 16:29 编辑 [/it]]