How to skip over a space when my while loop is supposed to stop at a space.

Hello! I really appreciate how this forum helped me understand my assignment. I have started on it but now I run into a problem and I don't really know how to get out of the rut.

Using stacks, I'm supposed to read in a text file, and when encountering certain characters, I pop/push the stack. One of these characters, '@' has a function:

"Text editors sometimes have a kill character, whose effect is to cancel the previous word on the current line. For the purposes of this example, we will use ‘@’ as the kill character. So, if the input is twinkle, twinkle little @ star then the stream of words is altered to twinkle, twinkle star"

And the algorithm my professor gave was:
" if the current character is @, then pop characters off the stack until a space is reached; otherwise, push the current character "

Now, I believe the reason why my code isn't working is that my while loop stops when the top of the stack is equal to a space. But the problem is when I try to get back to the characters I actually want to pop off, I can't because it is equal to a space. Like "twinkle, twinkle little @ star", my code will stop right before little because of the space. I would appreciate guidance for my code. Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  #include <iostream>
#include <fstream>
#include <stack>
using namespace std;


int main(){
  stack<char> stack, reverse;
  char c;
  ifstream fin;
  fin.open("proj3.txt");


fin >> noskipws;
  while(!fin.eof()){
      fin >> c;


  if(c == '#'){
      stack.pop();
  }

 else if(c == '@'){
    while (stack.top() != ' '){
     stack.pop();
   }
 }

   else{
     stack.push(c);
   }

}




while(!stack.empty()){
  reverse.push(stack.top());
  stack.pop();
}

while (!reverse.empty())
{
   cout << reverse.top();
    reverse.pop();
}

}


Last edited on
1
2
3
4
5
6
else if (c == '@') {
    while (!stack.empty() && stack.top() == ' ') // skip initial spaces
        stack.pop();
    while (!stack.empty() && stack.top() != ' ') // skip up to the next space
        stack.pop();
}

Note how you need to ensure the stack isn't empty, too.

And your initial while should be

 
while (fin.get(c))    // not !fin.eof() 

and you don't need the skipws part if you use get instead of >>.

If you want to test for any kind of whitespace and not just the space char, you can use isspace(stack.top()) instead of stack.top() == ' '.
Last edited on
Topic archived. No new replies allowed.