0
 1 #include<iostream>
 2 using namespace std;
 3
 4 #include"dstack.h"
 5
 6 int main()
 7 {
 8  char value = cin.peek();
 9  char op;
10  double num;
11
12  while(value != cin.eof())
13  {
14   if( (isdigit(value) || value == '.') )
15   {
16    cout << "you entered a digit!" << endl;
17    cin >> num;
18   }
19
20   else if( (isspace(value)) )
21   {
22    cout << "white space" << endl;
23    cin.ignore();
24   }
25
26   else if( (!isdigit(value)) )
27   {
28    cout << "You entered a character" << endl; // I want this to catch operators
29    cin >> op;
30   }
31  }
32  cout << "No more input" << endl;
33 }

Ok so basically what im trying to do is create a postfix calculator and implement a stack. I can figure that out, but im just trying to get the basic input for this program figured out, and im not familiar with cin.peek(). What I want to do is ignore whitespace with cin.ignore(), if the user enters a number 0-9 or a period( '.' ) i want to input a double, and if the user enters an operator( +, -, ^, /, *) then input a character. However, I can't figure out how to use cin.peek() correctly, if anyone can point me in the right direction it would be greatly appreciated. An example of an input would be something like 10 20 40++ (no spaces between numbers and operators, and operators and operators is acceptable) and then the user presses ctrl+d to end the input.

user1940516
  • 41
  • 1
  • 3
  • 6

1 Answers1

0

Well, in.peek() will read the current character or return std::char_traits<char>::eof() if EOF is reached. The expression in.eof() yield a Boolean flag indicating whether the stream has reached EOF at some point. That is, the loop condition would probably look something like this:

for (int c; (c = (std::cin >> std::ws).peek()) != std::char_traits<char>::eof(); ) {
    if (std::isdigit(c) || '.') {
       ...
    }
    ...
}

The expression reading the next character starts off with skipping whitespace (remove >> std::ws if you don't like that) and checks the result against the value return if EOF is reached after also storing it into the variable c.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380