我正在嘗試使用文件的內容作爲輸入,並將操作數,括號和運算符分開。由於輸入文件包含2行輸入,我以爲我應該一次讀取整行而不是一個值,因爲我不想混淆兩行的值。我在想什麼做的是將值壓入堆棧時出現Seg故障
- 使用函數getline和存儲一行在同一時間進入所謂的輸入
- 打破字符串的字符串變量(使用空格作爲分隔符)分割成段而推入堆棧稱爲tempContainer。
- 將tempContainer.top()存儲到臨時變量中並調用tempContainer.pop()
- 處理temp將操作數的括號分開並將它們存儲到兩個不同的變量中。
一切都很順利,直到我嘗試將最後一個數據推入堆棧。我在調用tempContainer.push(temp)之前檢查了這些值;並且一切都很好,所以我不明白爲什麼我會遇到分段錯誤。錯誤發生在運行時,而不是在編譯期間發生。
輸出產生:
A + B * (C - D * E)/F <-----The original line to break down. Line 1
A
+
B
*
(C
-
D
*
E)
/
F
AB * CDE + (RST - UV/XX) * 3 - X5 <-----Line 2
AB
*
CDE
+
(RST
-
UV
/
XX)
*
3
-
//Segmentation fault here
下面的代碼(使用錯誤的行是接近底部)
int main(int argc, char* argv[])
{
string input, temp;
fstream fin;
stack<string>aStack;
vector<string>sOutput;
stack<string>tempContainer;
int substr1, substr2;
fin.open(argv[1], ios::in);
if(!fin.good())
{
//...
}
else
{
while(!fin.eof())
{
getline(fin, input);
cout << input << endl; //For verifying the content of input. Delete later
if(input[0] == '\0') //To prevent reading the last data in a file twice
{
break;
}
else
{
//+++++++++++++++++++Breaking down string into sections++++++++++++++++++++
//Storing the unprocessed segments of the original string into a stack
//segments will be popped out later to be processed to separate parenthesis
substr1 = 0;
substr2 = 0;
for(int i = 0; i < input.length();)
{
while(input[i] != ' ')
{
substr2++;
i++;
}
temp = input.substr(substr1, substr2 - substr1);
substr2++;
substr1 = substr2;
i++;
tempContainer.push(temp); //ERROR here
cout << tempContainer.top() << endl; //For testing purpose, delete later.
}
//+++++++++++++++++++++Finish breaking down strings++++++++++++++++++++++
}
}
}
}
能不能幫我追查錯誤(縣)?感謝您的時間!
很難幫你這麼多的缺碼調試此。例如,變量聲明會很有用。 – GWW
@GWW我不敢發佈太多的東西,因爲我之前被建議直接提到這一點。我會立即解決這個問題 – Vince
你有沒有嘗試用調試器逐步執行代碼,並檢查'i'的值與字符串的長度比較?你在'for'循環之外迭代'i'多次,而不執行任何邊界檢查。 – GWW