C :在结构中以零为零的输出

C++: output with extra zero in struct

本文关键字:输出 结构      更新时间:2023-10-16

我是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;
}

i输出数据。那就是我得到的:

额外0的末尾不是我的期望。

顺便说一句。我想将结构放在数组中。使此功能适用于多个员工。我知道应该创建诸如applyepy型员工[5]之类的结构;我只是因为阅读文件而陷入困境。无法继续移动。

您尝试读取14个值,但是您的输入文件仅包含13个。因此,输出的最后一个值是employee.carsale0,如初始化中。

您读取14个参数,但您的文件只提供13。也许您忘了在employeeInfor.txt中添加一列。