【发布时间】:2015-03-05 20:41:54
【问题描述】:
我的 .txt 文件包含以下内容
12345
John Smith
45 12.50
54234
Joe Paul
32 10.25
12324
Chris Lee
43 22.50
第一个 int 是员工 ID,然后是字符串名称,然后是小时数和工资率(浮点数)。
我的程序:
using namespace std;
const int Size = 10;
typedef int intarray[Size];
typedef float farray[Size];
typedef string starray[Size];
void readdata(intarray,starray,intarray,farray, ifstream &);
void print(intarray,starray,intarray,farray,ifstream &);
int main()
{
ifstream fin("data.txt");
//ofstream fout;
starray EmployeeName;
intarray EmployeeID,EmployeeHoursWorked;
farray EmployeeRate;
readdata(EmployeeID,EmployeeName,EmployeeHoursWorked,EmployeeRate,fin);
print(EmployeeID,EmployeeName,EmployeeHoursWorked,EmployeeRate,fin);
cin.get();
cin.ignore();
}
我的函数,我的代码没有正确读取文件。
void readdata(intarray ID, starray Name, intarray Hours, farray Rate, ifstream & infile)
{
for(int i = 0; i < Size; i++)
{
//this code is not working as intended
infile >> ID[i];
getline(infile, Name[i]);
infile >> Hours[i] >> Rate[i];
infile.ignore();
}
}
我没有得到任何结果。
void print(intarray ID, starray Name, intarray Hours, farray Rate, ifstream & infile)
{
for(int i = 0; i < Size; i++)
{
cout << ID[i] << endl;
cout<<Name[i]<<endl;
cout << Hours[i] << Rate[i] << endl;
}
}
【问题讨论】:
-
Re: P.S.: 你可以用赋值语句将数据填充到数组中以解决读取问题。
-
一点点错误处理会大有帮助。尝试添加一些代码,例如
if (infile.bad()) cout << "can't read file";。 -
我很确定
print不应该读取任何文件。 -
是的,为什么你的
print函数附近有infile? -
哦,是的。小错误。它仍然给我错误的输出。它正确读取第一行“12345”然后吐出垃圾/随机数