我创建了一个函数,该函数将用户输入的字符串与最初从文件中拉出的结构数组内部的字符串进行比较。
我要测试的字符串列表是“奥斯丁,达拉斯,华盛顿特区和芝加哥”。除华盛顿特区外,每个城市都在运作,这使程序陷入无限循环。我已经尝试调试和重写部分代码,但是同一件事不断发生。
正在读取的文本文件
Austin,Houston,109,140
Washington D.C.,Seattle,139,421
Austin,New York,94,1511
Dallas,Austin,93,74
Chicago,Las Vegas,149,1039
第一个城市是出发城市。第二个城市是到达城市。然后,第一个数字是航班的费用,第二个数字是距离。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct data {
string departureCity;
string arrivalCity;
int cost;
int distance;
};
void readFlights(data flightList[], int& SIZE) {
ifstream inData("flights.csv"); // Opens csv file
string flightCost;
string flightDistance;
int i = 0;
// Goes through the csv file and assigns each string and int into a struct array
// Having issues where it reads an additional line even though it should read eof
while (!inData.eof()) {
getline(inData, flightList[i].departureCity, ',');
getline(inData, flightList[i].arrivalCity, ',');
getline(inData, flightCost, ',');
flightList[i].cost = stoi(flightCost);
getline(inData, flightDistance);
flightList[i].distance = stoi(flightDistance);
i++;
}
inData.close(); // Closes csv file
SIZE = i-1;
}
void printFlightsFrom(data flightList[], int SIZE) {
string userInput;
int i = 0; //array counter
bool cityCheck = false; //Checks to see if the users city was used.
cout << "Enter a city you are looking to depart from." << endl;
cin >> userInput;
cout << endl;
do {
if (!userInput.compare(flightList[i].departureCity)) {
cout << "Departure City: " << flightList[i].departureCity
<< " Arrival City: " << flightList[i].arrivalCity
<< " Cost: " << flightList[i].cost
<< " Distance: " << flightList[i].distance << endl;
cityCheck = true;
}
i++;
} while (i < 5);
if (cityCheck == false) {
cout << "You have entered an unavailable city. Returning to main menu." << endl;
}
}
int main() {
int SIZE = 100;
data flightList[SIZE]; //Creates an array of size 100 for storing the file data
readFlights(flightList, SIZE); //function that opens a file and writes the contents to a struc array
int menu_choice = 0;
do {
cout << "Select an action:" << endl;
cout << "2) Show the flights that depart from a given city" << endl;
cout << "4) Exit the program" << endl;
cin >> menu_choice;
switch (menu_choice) {
case 2: printFlightsFrom(flightList, SIZE);
break;
case 4: cout << "goodbye!" << endl;
break;
default: cout << "Invalid choice" << endl;
}
}while (menu_choice != 4);
return 0;
}
[进行调试时,“华盛顿特区”永远不会被识别为城市,因此程序会退回到main并继续通过menu_choice的开关。它再也不需要用户输入,并不断抽出main中的cout线。
非常感谢您的帮助
更新:字符串“华盛顿特区”仍然无法正确比较,我将无限循环问题缩小为do while循环。在menu_choice变量中键入字符后,它表示无效选择,然后再也没有给用户输入新的menu_choice的机会。它再次键入所有内容,然后当然是“无效选择”,然后无限期地继续循环。
cin >> userInput
实际上读取空间,因此仅读取“华盛顿”,以“ D.C.”开头。进入输入缓冲区。