使用getline和vector的C ++问题

时间:2013-04-08 20:18:02

标签: c++ vector getline

我有一个问题,我正在使用getline从文件中读取一行,并使用字符串流将逗号分隔为不同的变量作为分隔符。问题是变量的标准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;
}

reservation.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; }

};

1 个答案:

答案 0 :(得分: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;