2016-03-08 95 views
0

所以我必須輸入一個大學程序菜單,它使用字符串和數組來提出一系列問題。可變大小的對象數組可能無法初始化

我現在打印了這個。

`

#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’可能無法初始化錯誤,我真的不能點我的,爲什麼它不會手指:\得益於先進

+1

這是什麼:void populateArray(string * statesArray,int&sizeOfArray) int statesArray [] = {}; {...'? – user463035818

+2

爲什麼使用可變大小的數組擴展如果你可以使用'std :: vector'? – Jarod42

+2

由於您已經在使用vector,所以'statesArray'是一個向量。你不能創建一個在編譯時不知道大小的普通數組。 – NathanOliver

回答

0

變長數組(VLA的)是c++非標準所以這行也不行。

string statesArray [sizeOfArray] = {}; 

關於爲什麼有一個合理的好解釋here。至於你的例子,由於你已經在使用std::vector,你應該簡單地用std::vector<std:string>代替statesArray