我正在尝试使用文件的内容作为输入和单独的操作数,括号和运算符。由于输入文件包含2行输入,我认为我应该一次读取整行而不是值,因为我不想混淆两行中的值。我想做的是
一切顺利,直到我尝试将最后的数据推入堆栈。我在调用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++++++++++++++++++++++
}
}
}
}
你能帮我跟踪错误吗?感谢您的时间!
答案 0 :(得分:3)
你需要这样的边界检查:
while(i < input.length() && input[i] != ' ')
{
substr2++;
i++;
}