2013-11-28 82 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 
    } 
} 

所以基本上,你保存堆栈中的字符,如果它对应的。

相关问题