2017-10-21 13 views
1

私はRPNでテキストを含むファイルを持っていますが、各行は異なります。のは、例えば、最初の行を見てみましょう:私はそれぞれの行の合計をカウントする必要がC++逆ポーランド記法ファイルから読み取る

12 2 3 4 * 10 5/+ * + 

。これを行うには、スタックを使用する必要があります。これは次のように動作します:スタックに数値を追加する場合は+、 - 、*、/ - >スタックに2つの最新の数値を取り、それらの演算を行います。

問題は、私はファイルを読む瞬間に立ち往生しています。 (配列は文字を記憶している)場合

:私は、配列内の数字とサインを保存することを考えましたが、私はここで別の問題を持っている

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

入力ファイル形式でエンティティ間に少なくとも1つのスペースがあることが保証されている場合は、 'std :: ifstream'を使用し、数値と演算子を' std :: string'オブジェクトに読み込むことができます。 – navyblue

+0

数字は1つ以上の文字(10と12など)を占める可能性があるので、1文字配列は使用できません。 '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); 
    } 
} 
関連する問題