2017-10-21 45 views
1

我有一個包含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'將文本轉換爲數字。 –

回答

0

看一看這樣的:

#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); 
    } 
}