从文件中读取的C++反向波兰表示法

问题描述:

我有一个包含RPN中文本的文件,每行都不相同。我们以第一行为例:从文件中读取的C++反向波兰表示法

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”与下一行的第一个数字一起使用,这是我们不想要的。

+1

使用'的std :: string'和空格分割(成'的std :: string'数组)? – UnholySheep

+0

如果输入文件格式保证实体之间至少有一个空格,那么你可以使用'std :: ifstream'并将数字和运算符读入'std :: string'对象。 – navyblue

+0

您不能使用单个字符数组,因为数字可能会占用多个字符,例如10和12.如果将文本存储在'std :: string'中,则可以使用'istringstream'将文本转换为数字。 –

看一看这样的:

#include <fstream> 
#include <sstream> 
#include <string> 

void parseLine(const std::string& line) { 
    std::stringstream stream(line); 
    std::string token; 
    while(stream >> token) { 
     // Do whatever you need with the token. 
    } 
} 

int main() { 
    std::ifstream input("input.txt"); 
    std::string line; 
    while(std::getline(input, line)) { 
     parseLine(line); 
    } 
}