簡體   English   中英

通過ifstream的Char指針和字符串

[英]Char pointers and strings through ifstream

因此,我有一個遞歸下降解析器,可以很好地識別和通過命令行參數使用值,但我不確定如何將其移植到.dat文件中,使用適當的char指針,打印字符串,並為多個字符串工作。

使用命令行參數解析器:

#include <iostream>
#include <fstream>

using namespace std;

bool A(void);
bool E(void);
bool T(void);
bool F(void);
bool P(void);
bool I(void);
bool L(void);

char *c;

int main(int argc, char *argv[]){

    c = argc == 2 ? argv[1] : (char *)"";

    if (A() && *c == '\0') {
        cout << "The string \"" << argv[1] << "\" is in the language." << endl;
    }
    else {
        cout << "The string \"" << argv[1] << "\" is not in the language." << endl;
    }

    return 0;
}

bool A(void){

    if( I() )
    {
        if ( *c == '=' ){
            ++c;
            if ( E() )
            return true;
        }
    }
    return false;
}

bool E(void){

    if( T() ){
        if ( *c == '+' || *c == '-' ){
                ++c;
                return E();
        }
        return true;
    }
    return false;
}

bool F(void){

    if( P() ){
        if( *c == '^'){
            ++c;
            return F();
        }
    return true;
    }
    return false;
}

bool I(void){

    if ( *c >= 'a' && *c <= 'z'){
        ++c;
        return true;
    }
    return false;
}

bool L(void){

    if ( *c >= '0' && *c <= '9' ){
        ++c;
        return true;
    }
    return false;
}

bool P(void){

    if ( I() ){
        return true;
    }
    else
    if ( L() ){
        return true;
    }
    else
    if ( *c == '(' ){
            ++c;
            if ( E() ){
                    if ( *c == ')' ){
                        ++c;
                        return true;
                    }
            }
    }
    return false;
}

bool T(void){

    if( F() ){
        if ( *c == '*' || *c == '/' ){
                ++c;
                return T();
        }
        return true;
    }
    return false;
}

我不知道可以用什么替換argv [1]來打印字符串。 要獲取正確的char指針,我可以這樣做嗎?

ifstream fin("input.dat");
        while (fin >> *c)

當我嘗試得到細分錯誤時。

您正在要求流將值存儲到c指向的值所表示的內容中。 相反,請考慮:

char ch;
char *c = &ch;

ifstream fin("input.dat");
while (fin >> ch) {
    // whatever
}

這不會立即出現段錯誤。 但是,當您在解析函數中更改c的值時,“下一次”迭代會發生不好的事情。

您需要重新構造程序,並從讀取下一個字符的方法中抽象出讀取下一個字符的意圖 (通過增加指針或從流中讀取內容,等等)。

或者,您也可以將文件讀取到一個大內存緩沖區中,然后繼續進行操作,就好像該緩沖區是從命令行傳遞的字符串一樣。

假設您的文件是一個文本文件,每行只有一個條目要解析,則可以執行以下操作:

ifstream fin("input.dat")
if (fin.is_open())
{
    std::string line;
    while (fin.good())
    {
       getline(fin, line);
       c = line.c_str();
       ... go and parse c
    }
}

更新 :顯然c是非常量的,因此使用c_str()不能那樣工作。 您有兩種選擇:

  1. 更改您的解析器以使用std :: string(使用索引指向當前字符)。
  2. 分配一些內存,然后在其中復制c_str()

1號可能是更好的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM