2013-11-28 37 views
1

我在一個項目上工作,遇到了我認爲我忽視了一個簡單的操作或其他東西。如何只讀取文件中的特定字符?

問題的一個例子是從指定文件中查找'%'或'*'字符。

當他們被找到時,我會將它們壓入堆棧,然後移動到文件中的下一個字符。

例如

ifstream fin; 
fin.open(fname); 

while (fin.get(singlechar)){  //char singlechar; 

if (singlechar == '(' || singlechar == ')' || singlechar == '{' || singlechar == '}' || > singlechar == '[' || singlechar == ']') 

    Stack::Push(singlechar); //push char on stack 

什麼是做到這一點的好辦法? for循環,做while循環? getline而不是singlechar?

回答

0

已經有一個existing question的答案。這裏:

char ch; 
fstream fin(filename, fstream::in); 
while (fin >> noskipws >> ch) { 
    cout << ch; // Or whatever 
    //In your case, we shall put this in the stack if it is the char you want 
    if(ch == '?') { 
     //push to stack here 
    } 
} 

所以基本上,你保存堆棧中的字符,如果它對應的。

相關問題