簡體   English   中英

如何逐行讀取文本文件然后解析行中的字符?

[英]how to read text file line by line then parse charaters in a line?

我正在從一個文本文件中讀取一個中綴表達式,我想將其轉換為后綴表達式。

例如,這是文本文件中的內容

1+1
2+2

我一次讀取一行表達式,如下所示

 char c;
 string readLine; 
ifstream txtfile("a1.txt");
 while ( getline (txtfile,readLine) ) // read line by line
    {
        cout << readLine << endl;

        // how can I set c to be the first character from the read line


         infix_to_postfix(stack, queue,c );

    }

我的問題是如何讓變量C等於讀取行的第一個字符,以便可以將其發送到我的infix_to_postfix函數? 然后第二個字符..一直到行尾。

當第一行被完全讀取時,我想讀取第二行並一次將一個字符發送到我的infix_to_postfix函數。 我希望我在這里很清楚,謝謝!

對單個字符使用get方法:

char c;
std::ifstream txtfile("a1.txt");
while (std::getline(txtfile, readLine))
{
    while (txtfile.get(c))
        infix_to_postfix(stack, queue, c);
}

您還可以使用std::stringstream

#include <sstream>

// insert the following inside the getline loop

std::stringstream ss(ReadLine);

char c;

while (ss >> c) 
    infix_to_postfix(stack, queue, c);

您可以使用帶有索引的常規for循環從std::string迭代字符,如下所示:

for (int i = 0 ; i != readLine.size() ; i++) {
    infix_to_postfix(stack, queue, readLine[i]);
}

或使用迭代器:

for (string::const_iterator p = readLine.begin() ; p != readLine.end() ; ++p) {
    infix_to_postfix(stack, queue, *p);
}

兩個片段之間在性能方面幾乎沒有差異,因此選擇取決於您。

暫無
暫無

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

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