嗨慷慨的StackExchange人,
我正在使用C ++,我似乎遇到了无法正确匹配两个字符串值的错误。我在main中有代码:
/**
* 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
行只是没有用。我现在坚持这一点。
这是它正在阅读的文本文件:
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
我必须真正完成我的任务,但我无法弄清楚如何解决这个问题。请帮帮我。
答案 0 :(得分:1)
我感谢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);
}