gpt4 book ai didi

c++ - 字符串值与 C++ 不匹配

转载 作者:太空宇宙 更新时间:2023-11-04 11:44:10 26 4
gpt4 key购买 nike

大家好,StackExchange 的慷慨人士,

我正在使用 C++,我似乎遇到了无法正确匹配两个字符串值的错误。我有主要的代码:

/**
* Author: Kevin Hill
* Assignment: Project5
* Description: VehicleDB
**/

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include "Vehicle.h"
//#include "Truck.h"
//#include "Car.h"

using namespace std;

bool checkLine(string, string);

int main(int argc, char const *argv[])
{

string fileName; //This is the file name
//Vehicle array
ifstream file; //Instantiate file
string sLine;
Vehicle **vehArr;

//Tell user to enter data
cout << "Enter the file name: ";
cin >> fileName;
file.open(fileName.c_str());
if(!file.is_open()){
cerr << "The file is not there" << endl;
return 1;
}


//Get first line of file to determine size of vehArr
for (int i = 0; !file.eof(); ++i)
{
if (i == 0){
getline(file, sLine);
break;
}
}

int arrSize = atoi(sLine.c_str());
vehArr = new (nothrow) Vehicle*[arrSize];
string truck = "truck";
string car = "car";
while(!file.eof()){
getline(file, sLine);
string stuff = sLine;
checkLine(stuff, car);
}

// Test add Truck and Car objects
// vehArr[0] = new Car(file);
// vehArr[1] = new Truck();

string theLine = "";

// checkLine("one", "one");

// cout << "Beginning loop" << endl;

// for (int i = 0; !file.eof(); ++i){
// getline(file, theLine);



// // if(theLine == "car"){
// // vehArr[i] = new Car(file);
// // i++;
// // }
// // if (theLine == "truck"){
// // vehArr[i] = new Truck(file);
// // i++;
// // }
// // if (i == arrSize){
// // break;
// // }
// }

return 0;
}

bool checkLine(string one, string two){

// if (one == two)
// {
// /* code */
// }



if (one == two)
{
cout << "It's a " << two << endl;
}
// cout << one << endl;
// cout << two << endl;

return true;
}

如您所见,我对代码进行了注释,以去除对我的问题不重要的所有内容。当我阅读我的文件时,我尝试匹配所有等于 car 的行。它应该可以工作,因为我尝试让所有行都相等并且行得通,但是让行单独等于 car 只是行不通。我现在被困在这件事上。

这是它正在读取的文本文件:

5
car
11111
Ford
Fusion FWD
Red
24999.00
3
AC
795.00
XM
295.00
Leather Seats
495.00
20
28
car
22222
Volvo
V70 FWD
White
42999.00
2
Child Seats
198.00
17" wheels
698.00
14
22
car
33333
Honda
Accord
Silver
19999.00
1
Tinted Windows
175.00
22
31
truck
44444
Freightliner
FLD SD
Red
119999.00
1
Detroit Diesel Series 60
4999.00
10 speed manual
455
truck
55555
Mack
TerraPro Cabover MRU612
White
125000.00
1
Dual Air Brake System
6000.00
8 speed manual
325

我必须真正完成我的任务,但我不知道如何解决这个问题。请帮助我。

最佳答案

感谢 WhozCraig 给我答案。可能会出现索引问题,因为我使用了 !file.eof() 而不是 file >> data

所以这是次要的代码差异:

string truck = "truck";
string car = "car";
//Old version
while(!file.eof()){
getline(file, sLine);
string stuff = sLine;
checkLine(stuff, car);
}

string data;
while(file >> data){
// cout << data << endl;
checkLine(data, car);
}

关于c++ - 字符串值与 C++ 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319269/

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