使用矢量、字符串和数组创建菜单,同时读取2个文本文件

Creating a menu using vectors, strings and arrays while reading from 2 text files

本文关键字:读取 2个 文件 文本 菜单 创建 字符串 数组      更新时间:2023-10-16

好吧,我已经试了几个小时了,但没有取得任何进展。第一个总之,我有两个文本文件,我需要从一个不同的函数中读取,这很简单。然后,对于其中一个文本文件,主要是college.txt,我必须将其添加到字符串向量中;对于另一个文本文件(states.txt),我必须将状态添加到字符串的并行数组中。

我遇到的问题(这与college.txt文件有关)是如何将用户输入的字符串与向量内的字符串进行比较,因为我必须验证用户输入的学院/大学是否在列表上(当然也要重复,直到用户决定退出,但这也很简单,只需执行while循环)。

注1:在你问之前,else/if语句为空,因为我想先关注这个问题,然后再继续这个程序。

注2:我使用的IDE是CodeBlocks

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
bool DoesStringEqualVector(vector<string> total, string name)
 {
    for (unsigned int i=0; i < total.size(); ++i)
  {
    if (name == total[i])
          return true;
  }
  return false;
 }
void collegesUniversities(string)
{
ifstream campuses;
campuses.open("colleges.txt");
string schools;
vector<string> schoolVector;
if(!campuses)
    cerr << "Error opening file. ";
else
{
  while(campuses.good())
   {
     getline(campuses,schools, 'n');
     schoolVector.push_back(schools);
     cout << schools << endl;
   }
}
DoesStringEqualVector(schoolVector, schools);
campuses.close();
}
int main()
{
char response;
string comparison;
int choice;
string userInput;
cout << "nWelcome to my college and university search program.n";
cout << "nPress any button to continue.n ";
                      system("pause>nul");
do
{
 cout << "nPress 1 to enter possible colleges and universities.";
 cout << "nPress 2 to find out how many colleges and universities";
 cout << " appear in your state.n";
 cout << "Press 3 to find the total amount of colleges and";
 cout << " universities in our list. ";
 cout << "nPress 4 to quit. ";
 cin >> choice;
  if(choice == 1)
 {
   do
    {
      cout << "nEnter the name of your college/university. ";
      cin >> userInput;
      collegesUniversities(comparison);
      if(userInput != comparison)
        cout << "nThis institution isn't on out list.n ";
      else
        cout << "nThis institution is on the list.n";
      cout << "nWould you like to return to the menu?[Y/N] ";
      cin >> response;
      while(response != 'Y' && response != 'y' && response != 'N' &&
          response != 'n')
      {
          cerr << "nError, Invalid Input.";
          cin >> response;
      }
    }
    while(response != 'N' && response != 'n');
   }
   else if(choice == 2)
   {
   }
  else if(choice == 3)
   {
   }
  else if(choice == 4)
   {
    cout << "nThank you for using my program. ";
    cout << "Have a great day.n ";
   }
  else
   {
    cerr << "nError, Invalid input. ";
    cout << "Only integers from 1 through 4 are allowed.n";
   }
  }
   while(choice != 4);
}

用一个检查向量的方法将其全部封装起来:

bool IsStringInVector(vector <string> collection, string item)
{
    for (int i=0; i < collection.size(); ++i)
    {
        if (item == collection[i])
              return true;
    }
    return false;
}

你必须扫描藏品,看看它是否在里面。