【发布时间】:2017-10-21 17:42:45
【问题描述】:
我有一个包含 RPN 文本的文件,每一行都是不同的。我们以第一行为例:
12 2 3 4 * 10 5 / + * +
我需要计算每一行的总数。为此,我需要使用堆栈。它的工作原理是这样的:如果有一个数字 -> 将其添加到堆栈中,如果它是 +、-、* 或 / -> 在堆栈中获取两个最新的数字并对它们进行上述操作。
问题是,我在读取文件时卡住了。我正在考虑将数字和符号存储在数组中,但这里还有另一个问题:
如果(数组存储字符):
array[0] = '1',
array[1] = '2',
array[2] = ' ',
如何将它变成 int 12(空格表示它是数字的结尾)?有没有一种简单快捷的方法可以做到这一点? 或者也许有更好的方法来读取文件并将其放入堆栈?
感谢有关使用字符串存储数据的建议,我做到了,这里是实现:
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
int main(){
stack <int> stos;//the name is a bit weird but it's just 'stack' in polish
ifstream in("Test1.txt");//opening file to read from
string linia;//again - "linia" is just "line" in polish
int i = 1;//gonna use that to count which line i'm in
while (getline(in, linia, ' ')){
if (linia == "*"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
stos.push(a*b);
}
else if (linia == "+"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
stos.push(a+b);
}
else if (linia == "-"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
stos.push(a-b);
}
else if (linia == "/" || linia == "%"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
int c = a / b;
stos.push(c);
}
else if (linia == "\n"){
cout << "Wynik nr " << i << ": " << stos.top() << endl;
stos.pop();
i++;
}
else{//if it's a number
stos.push(atoi(linia.c_str()));
}
}
}
文件如下所示:
12 2 3 4 * 10 5 / + * +
2 7 + 3 / 14 3 - 4 * +
每行前非第一行的空格是必须的,否则程序会将“\n”与下一行的第一个数字一起使用,这是我们不想要的。
【问题讨论】:
-
使用
std::string并用空格分割(成std::string的数组)? -
如果输入文件格式保证实体之间至少有一个空格,那么您可以使用
std::ifstream并将数字和运算符读取到std::string对象。 -
您不能使用单个字符数组,因为数字可能占用多个字符,例如 10 和 12。将文本存储在
std::string,您可以使用istringstream将文本转换为数字.