gpt4 book ai didi

c++ - 使用 getline 和 vector 的 C++ 问题

转载 作者:行者123 更新时间:2023-11-30 04:19:22 25 4
gpt4 key购买 nike

我遇到一个问题,我正在使用 getline 从文件中读取一行,并使用 stringstream 使用逗号作为分隔符来分隔不同的变量。问题是变量的标准 cout 正确显示了 seatDes,但是使用 vector 我得到了名称而不是 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; }

};

最佳答案

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;  

关于c++ - 使用 getline 和 vector 的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15888169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com