2017-03-22 15 views
-2

我試圖創建一個從文件中讀取文本並搜索某些單詞的程序,然後從那裏進行處理。我正在使用數組來存儲我想要的數據,但是當我嘗試訪問數組之外​​的數組時,只有數組中的第一個點被佔用,並且是由函數讀取的最後一個值。當然代碼是不完整的,但我需要知道,這是什麼原因造成的?爲什麼我的數組之外的數組保留了任何值?

#include<iostream> 
#include<string> 
#include<fstream> 

using std::cout; using std::cin; using std::endl; using std::string; 
using std::ifstream; using std::getline; 

string data, strL = "language", strC = "created", strT = "timestamp"; 
string lang[2], date[2]; 
int count = 0, l = 0, c = 0; 
ifstream rawData("testsample.txt"); 

void search(int count, string data, string heading) { 
int x, y; 
if (data.find(heading) != string::npos) { 
    //cout << heading << endl; 
    if (heading == strL) { 
     x = 4; y = 2; 
     lang[count] = data.substr(data.find(strL) + strL.length() + x, y); 
     //cout << lang[count] << endl; 
    } 
    if (heading == strC) { 
     x = 4; y = 29; 
     date[count] = data.substr(data.find(strC) + strC.length() + x, y); 
    } 
} 
count++; 
} 

int main() { 
while (getline(rawData, data)) { 
    search(l, data, strL); 
    search(c, data, strC); 
    //count++; 
}cout << lang[0] << " " << lang[1] << endl; 
cout << date[1]; 

return 0; 
}  
+2

顯示的代碼是不可比較的混沌。全局變量。奇怪的,不合邏輯的縮進,隨機消失,在地方。魔術常數。無論它試圖做什麼,它都是不對的,沒有辦法使它正確無誤,從頭開始。 –

回答

0

我認爲你的問題就在於,你有全局變量count,也是一個參數來search功能countsearch函數中的count++聲明遞增參數,而不是全局。由於此功能中沒有循環,因此分配給langdate的索引始終爲零。

刪除參數可能會導致代碼做你想做的事情,但是,如果你處理兩個以上的,你會溢出。您可能會考慮使用std::vector或其他動態調整大小的容器類。

相關問題