2014-03-30 49 views
0

任何人都可以告訴我爲什麼對下面的變量所做的更改沒有被拉到main?如何從void(C++)返回多個值爲main(C++)

我很新,所以請保持簡單。

如果你需要更多的我的代碼讓我知道:d

void BannedWordsArrayCreate (string filePathInBanned, vector<string> bannedWords, vector<int> bannedWordsCount, vector<int> containsBannedWordsCount) { 

cout << "Please enter the file path for the banned word list. (no extension.): " << endl; //User enters file name 
cout << "E.g. C:\\Users\\John\\banned" << endl; 
cin >> filePathInBanned; 
filePathInBanned += ".txt"; //Takes User defined file name and adds .txt 

ifstream inFile; 
inFile.open(filePathInBanned,ios::in); //opens file 

if (!inFile) //if file cannot be opened: exits function. 
{ 
    cerr << "Can't open input file." << filePathInBanned << endl; 
    exit(1); 
} 

else if (inFile.is_open()) //if file opens: puts file into vector. 
{ 
    string bw = "nothing"; //temporary string used to signal end of file. 
    while(!inFile.eof() && bw != "") 
    { 
     inFile >> bw; 
     if (bw != "") 
     { 
      bannedWords.push_back(bw); 
     } 
    } 
} 
inFile.close(); 
cout << endl << "Done!" << endl << endl; 

for(int i = 0; i < bannedWords.size(); i++) 
{ 
    bannedWordsCount.push_back(0); 
    containsBannedWordsCount.push_back(0); 
} 
} 

回答

2

這條線......

void BannedWordsArrayCreate (string filePathInBanned, 
    vector<string> bannedWords, vector<int> bannedWordsCount, 
    vector<int> containsBannedWordsCount) 

...需要通過參考(索要變量&令牌)...

void BannedWordsArrayCreate (string& filePathInBanned, 
    vector<string>& bannedWords, vector<int>& bannedWordsCount, 
    vector<int>& containsBannedWordsCount) 

引用基本上是別名或原始變量的替代名稱(由調用者提供),因此對「引用」所做的更改實際上是修改了原始變量。

在你原有的功能,函數的參數是按值,這意味着在調用上下文中的變量拷貝傳遞,函數只得到對這些副本的工作 - 以副本的任何修改都將丟失函數返回時。


另外,!inFile.eof()未正確使用。關於這個問題有很多Stack Overflow Q/A,但是總的來說eof()標誌只能在流知道你要轉換的內容之後才能設置(例如,如果你嘗試讀取一個字符串並且它只能找到很多空白,然後它會失敗並設置eof,但如果你問流的下一個字符是什麼(包括空格),那麼它會成功返回該字符而不擊中/設置eof)。您可以將輸入處理簡化爲:

if (!(std::cin >> filePathInBanned)) 
{ 
    std::cerr << "you didn't provide a path, goodbye" << std::endl; 
    exit(1); 
} 

filePathInBanned += ".txt"; //Takes User defined file name and adds .txt 

if (ifstream inFile(filePathInBanned)) 
{ 
    string bw; 
    while (inFile >> bw) 
     bannedWords.push_back(bw); 
    // ifstream automatically closed at end of {} scope 
} 
else 
{ 
    std::cerr << "Can't open input file." << filePathInBanned << std::endl; 
    exit(1); 
} 
+0

謝謝,幫助了一堆。有趣的是它只是一件小事。 –

+1

@ Kiku-Suma歡迎您。上面的一些額外的反饋。乾杯。 –

1

您的所有參數都按值傳遞。這意味着當您調用該函數時,您傳入的對象將被複制。所以,當他們在函數內部改變,這些改變都對副本執行,而不是你在通過原來爲了解決這個問題,通過引用傳遞:

void BannedWordsArrayCreate (string& filePathInBanned, vector<string>& bannedWords, vector<int>& bannedWordsCount, vector<int>& containsBannedWordsCount) 

&對象類型後說,我們要將內存地址複製到該函數而不是該對象。所以,當我們對函數內的對象進行更改時,我們正在更改我們傳入的地址處的內存。原始內容已更改。