我是C ++的初学者,刚开始学习struct。 我创建结构并从文件中读取数据。
这是我的档案:
John Smith 26832904 1657 Commerce st Flushing NY 11204 7183942833 company01 962 51
我成功地将数据输入到结构中。输出很完美,但最后只有零,这可能让我发疯。
这是我的全部代码:
#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;
struct nametype
{
string first;
string last;
};
struct addresstype
{
string address1;
string address2;
string address3;
string city;
string state;
string zip;
};
struct contacttype
{
string home;
string person;
};
struct employeeType
{
nametype name;
string id;
addresstype address;
contacttype contact;
string worklocate;
double basewage;
int carsale;
};
int main()
{
ifstream infile;
infile.open("employeeInfor.txt");
if (!infile)
{
cout << "Error." << "\n";
}
employeeType employee;
employee.basewage = 0.0;
employee.carsale = 0;
infile >> employee.name.first >> employee.name.last
>> employee.id
>> employee.address.address1 >> employee.address.address2
>> employee.address.address3 >> employee.address.city
>> employee.address.state >> employee.address.zip
>> employee.contact.home >> employee.contact.person
>> employee.worklocate
>> employee.basewage >> employee.carsale;
cout << employee.name.first <<" "<<employee.name.last
<< " " << employee.id
<< " " << employee.address.address1 << " " << employee.address.address2
<< " " << employee.address.address3 << " " << employee.address.city
<< " " << employee.address.state << " " << employee.address.zip
<< " " << employee.contact.home << " " << employee.contact.person
<< " " << employee.worklocate
<< " " << employee.basewage << " " << employee.carsale << "\n";
infile.close();
system("pause");
return 0;
}
我输出数据。这就是我得到的:
顺便说一下。我想把结构放在数组中。使此功能适用于多个员工。我知道应该创建类似employeeType员工的结构[5]; 我只是停止阅读文件。无法继续前进。答案 0 :(得分:0)
您尝试读取14个值,但输入文件仅包含13.因此,您输出的最后一个值employee.carsale
与初始化中的0
一样。
答案 1 :(得分:0)
您阅读了14个参数,但您的文件仅提供了13.可能您忘记在employeeInfor.txt
中添加列。