1

我有一个问题,我正在使用 getline 从文件中读取一行,并使用 stringstream 使用逗号作为分隔符来分隔不同的变量。问题是变量的标准 cout 正确显示了 seatDes,但是使用向量我得到了名称而不是 seatDes。不知道为什么会这样。

文件中的标准行:Jane Doe,04202013,602,1A

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>

#include "reservation.h"

int main(int argc, char **argv)
{
std::ifstream flightFile;
std::string name, date, seatDes, flightNum, line;
int error = 0, conFlightNum;

flightFile.open("reservations.txt");

if(!flightFile)
{
    //returns a error value if there is a problem reading the file
    error = 1;
    return error;
}
else
{
    //Start reading files and sticks them into a class object and sticks the object into         the vector set        
    while (std::getline(flightFile, line))
    {
       std::istringstream ss(line);
       std::getline(ss, name, ',');
       std::getline(ss, date, ',');
       std::getline(ss, flightNum, ',');
       conFlightNum = atoi(flightNum.c_str());
       ss >> seatDes;
       reservation newRes(name, date, conFlightNum, seatDes);
       std::cout << name << std::endl << date << std::endl << conFlightNum << std::endl << seatDes << std::endl;
       std::cout << "Vector Component" << std::endl;
       std::cout //<< newRes.getName() << std::endl << newRes.getDate() << std::endl << newRes.getFlightNum() 
       << std::endl << newRes.getSeatDesg() << std::endl;
    }
}


flightFile.close();
return 0;
}

保留.h 文件

class reservation {
private:
std::string name, seatDesg, date;
int flightNum;

public:
//Default Constructor
reservation(){}
//Big Constructor
reservation(std::string name, std::string date, int flightNum, std::string seatDesg)
{
    this->name = name;
    this->seatDesg = name;
    this->date = date;
    this->flightNum = flightNum;
}

//Setters
void setName(std::string name)
{ this->name = name; }

void setFlightNum(int flightNum)
{ this->flightNum = flightNum; }

void setSeatDesg(std::string seatDesg)
{ this->seatDesg = seatDesg; }

void setDate(std::string date)
{ this->date = date; }

//Getters
std::string getName()
{ return name; }

std::string getSeatDesg()
{ return seatDesg; }

std::string getDate()
{ return date; }

int getFlightNum()
{ return flightNum; }

};
4

1 回答 1

2
reservation(std::string name, std::string date, int flightNum, std::string seatDesg)
{
    this->name = name;
    this->seatDesg = name;  // Here is your problem
    this->date = date;
    this->flightNum = flightNum;
}

应该

this->seatDesg = seatDesg;  
于 2013-04-08T20:28:35.420 回答