所以我必须输入一个大学程序菜单,用菜单和数组询问一系列问题。
我目前打了这个类型。
`
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
vector<string> populateVector();
void populateArray(string *, int &);
void menu();
int main()
{
vector<string> collegesVector = populateVector();
int sizeOfArray = collegesVector.size();
string statesArray [sizeOfArray] = {};
populateArray(statesArray, sizeOfArray);
cout << "\nWELCOME TO MY COLLEGE AND UNIVERSITY SUMMARY PROGRAM."
cout << "\n Press 1 to enter possible colleges and universities and the program will tell you if they appear on the list."
system("pause>nul");
do
{
cout << "\nPress 1 to enter possible colleges and universities and the program will tell you if they appear on the list.";
cout << "\nPress 2 to find out how many colleges and universities appear in the state of your choice.";
cout << "\nPress 3 to find out how many colleges and universities appear on our list in total.";
cout << "\nPress 4 to quit";
if (choice == 1)
{
do
{
cout << "Please enter the name of your college or university. ";
cin >> userInput;
collegesVector(resemblance);
if(userInput != resemblance)
cout << "\nThe institution you've entered is not on the list.\n";
else
cout << "\nThe institution you've entered is on our list!.\n";
}
}
}
vector<string> populateVector()
{
string marker;
string entry;
vector<string> collegesVector;
fstream inputFile;
inputFile.open("colleges.txt");
if (!inputFile)
{
cout << "cannot read";
return vector<string>();
}
getline(inputFile, marker);
while(!inputFile.eof())
{
getline(inputFile, entry);
if(entry.length() > 0)
{
collegesVector.push_back(entry);
}
}
inputFile.close();
return collegesVector;
}
void populateArray(string * statesArray, int & sizeOfArray)
int statesArray[] = {};
{
fstream inputFile;
string marker;
string entry;
inputFile.open("states.txt");
if (!inputFile)
{
cout << "cannot read";
return;
}
getline(inputFile, marker);
for(int i = 0; i < sizeOfArray; i++)
{
getline(inputFile, entry);
if(entry.length() > 0)
{
statesArray[i] = entry;
}
}
inputFile.close();
}
它继续给我“可变大小的对象'statesArray'可能没有初始化错误,我真的无法指出为什么它不会:\感谢先进。
答案 0 :(得分:0)
可变长度数组(VLA)在c++
中是非标准的。所以这一行不行:
string statesArray [sizeOfArray] = {};
关于为什么,有一个相当不错的解释here。至于您的示例,由于您已经在使用std::vector
,因此您只需将statesArray
替换为std::vector<std:string>
。