subsructing getchar's return value - c++

Suppose I have a file which is consists of a single string
a1
If I write this:
char ch = getchar();
char ch1 = getchar();
cout << ch - 'a' << " " << ch1 - '0' << endl;
I have 0 1 in output. But if I write this:
cout << getchar() - 'a' << " " << getchar() - '0' << endl;
I have -48 49.
Doesnt getchar() return a normal char? Why the result isn't the same?

You're getting the issue because the two calls to getchar() are evaluated in unspecified order, and your compiler happens to evaluate the rightmost one first.
C++ has rather loose rules regarding order of evaluation of subexpressions in an expression, to allow for more optimisation opportunities. The cout line is one expression, where the following is guaranteed:
the first getchar() will be evaluated before the first -
the second getchar() will be evaluated before the second -
the first - will be evaluated before the first <<
the second - will be evaluated before the third <<
the <<s will be evaluated in order from the left.
Note that there are no other ordering restrictions. For example, the compiler is free to evaluate both getchar() calls and both -s before the first <<. Most importantly, there is no rule forcing the first getchar() to be evaluated before the second one.

Related

Creating a postfix calculator in C++?

I have an assignment where I need to create a postfix calculator. I'm running into some difficulties that previous questions regarding the subject on SO didn't cover adequately.
Here's an example of input I want to handle:
12 6 +
2 *
[Carriage return]
Result: 36
The description of the assignment:
The arithmetical expressions we normally use are infix expressions, meaning that the operator appears between its two operands, as in "4 + 5". In postfix expressions, the operator appears after its operands, as in "4 5 +". Here is a slightly more complex postfix expression: "25 12 7 - 2 * /". The equivalent infix expression is: "25 / ((12 - 7) * 2)". The result of that expression should be 2.5 (don't use integer division). Postfix expressions don't require parentheses.
Write a program that uses a stack to evaluate postfix expressions.
Each input expression should be entered on its own line, and the
program should terminate when the user enters a blank line. The only
symbols in an expression will be +, -, *, /, digits and spaces.
Hint: Read a postfix expression from left to right. When you read a
number, push it on the stack. When you read an operand, pop the top
two numbers off the stack, apply the operator to them, and push the
result on top of the stack. At the end, the result of the expression
should be the only number on the stack.
Here's my code so far:
#include <list> /* Linked Lists */
#include <stack> /* Stacks */
#include <iostream> /* cout cin */
int main() {
std::stack< double, std::list<double> > postfixStack;
std::string input;
std::cout << "Enter a postfix expression: ";
std::getline(std::cin, input);
while (input != "") {
std::cout << "Input expression: " << input << std::endl;
for (int i = 0; i<input.length()-1; i++) {
if (input.compare(i, 1, " ")) { // should ignore spaces, but doesn't
std::cout << "Skipping element " << i << " \n";
} else if (static_cast<int>(input[i]) == input[i]) { // push numbers onto the stack
postfixStack.push(static_cast<double>(input[i]));
std::cout << "Pushing " << input[i] << " onto the stack.\n";
} else if (input.compare(i, 1, "+")) { // pop two numbers off the stack (1), apply the operator to them (2), and push that onto the stack (3)
double operand1 = postfixStack.top();
postfixStack.pop();
double operand2 = postfixStack.top();
postfixStack.pop();
postfixStack.push(operand1 + operand2);
std::cout << "Adding " << operand1 << " and " << operand2 << std::endl;
}
}
std::getline(std::cin, input);
}
if (!postfixStack.empty()) {
std::cout << "Result of expression: " << postfixStack.top() << std::endl;
} else {
std::cout << "It appears that you did not enter an expression to evaluate.\n";
}
return 0;
}
Syntax highlighting and line numbers on Gist.
Where I'm struggling:
My while loop should allow more than one line of input per the spec. I was originally using cin instead of getline, but that presented the opposite problem: unlimited lines to enter anything whatsoever, even when checking for /r and the empty string.
I'm trying to skip over spaces in my loop, but instead my conditional appears to skip over anything that isn't a space.
Checking string subscripts means that I can only use numbers with one digit, which definitely isn't what I want. When I encounter a number: I think I could check the next element, if that's a number then I could concatenate them and bump up the loop counter. In theory, at least. I'd like to get basic functionality before I work on that.
My while loop should allow more than one line of input per the spec.
You've already found getline. You can simply use that to read whole lines. That approach you've taken looks fine.
I'm trying to skip over spaces in my loop, but instead my conditional appears to skip over anything that isn't a space.
That's right. You're checking the result of string::compare, but the result isn't a boolean, and non-zero doesn't mean the strings are equal, it means they aren't equal.
The way you've performed the comparison is uncommon, BTW, and more usual would be to simply compare the character to ' ', or to use isspace or maybe isblank.
Checking string subscripts means that I can only use numbers with one digit, which definitely isn't what I want.
Right. When you see a digit, you can enter a nested loop to read all subsequent digits. The base case, a one-digit string, is trivially converted to a number. (But just a tad less trivial than you think, see the note below.) And if you know how to determine the value of an N-digit string (let's say ABC), you can determine the value of an N+1-digit string (let's say ABCD) by multiplying by 10, and adding the value of the next digit.
Note: static_cast<int>(input[i]) == input[i] is always true. This doesn't mean what you think it means. Use your debugger to inspect the value of static_cast<int>(input[i]) for some characters, and try to understand what this cast is doing. When you understand what this does, think about another check you could do instead, and how you can use that, after checking a character is a digit, to determine the numeric value of that digit.

Logical operations in cout [duplicate]

This question already has an answer here:
The output of cout << 1 && 0;
(1 answer)
Closed 7 months ago.
Consider:
int i = 56, j = 0;
int n = i&&j;
cout << i&&j;
cout << endl << n;
whose output would be:
56
0
I imagine it's either because of operator precedence or logical short circuit, but I can't seem to figure out which, or the reason.
The expression cout << i&&j is equivalent to (cout << i) && j. Both operands are evaluated and converted to bool. The statement as a whole has no effect, but the evaluation of the subexpression cout << i has the usual side effects, of course, namely writing something to the standard output.
The && operator is indeed short-circuited and j is only evaluated if cout << i evaluates as true. This condition is equivalent to cout.good(), which is usually the case (unless you somehow managed to close your standard output).
As you expected, the << operator comes takes precedence over &&.
Thus, cout << i&&j first outputs i, then compares the returned stream to j (both are true, so the returned value is true, but this value is discarded).
See here for the full list of operator precedence.

cout and sizeof are not returning what I expect in C++

Here is sth I find but I can't understand one address ,when I use "cout<
#include<iostream>
using namespace std;
int main()
{
char a[2]={'a','b'};
char b[3]="ab";
cout<<&a<<endl;
cout<<&b<<endl;
cout<<sizeof(a)<<endl<<cout<<sizeof(b);//the result of this I am puzzled
return 0;
}
The result is :
0x28ff2e
0x28ff10
2
0x4453c43
0x28ff2e is an address of a
0x28ff10 is an address of b
2 is the size of a
0x4453c43 is an address of the result of converting cout to void* followed by sizeof(b) (See Does std::cout have a return value?)
Maybe you did want this instead:
cout << sizeof(a) << endl;
cout << sizeof(b) << endl;
Or this:
cout << sizeof(a) << endl << sizeof(b) << endl;
When you do this line:
cout<<sizeof(a)<<endl<<cout<<sizeof(b)
You shouldn't use cout second time. When you do, you printf address of it:
0x4453c4
or rather Does std::cout have a return value?
and then you print size of b, is the 3 on the end of this 0x4453c43
Rather you should just use this:
cout<< sizeof(a) << endl << sizeof(b) << endl;
You're printing the address of cout ;)
cout<<sizeof(a)<<endl<<cout<<sizeof(b)
The problem is that you're streaming the cout object to itself, so it prints whatever the cout can be converted to that operator<< if overloaded for - which happens to be void* (before C++11, which you evidently aren't using).
Either break cout<<sizeof(a)<<endl<<cout<<sizeof(b); into two lines with a semicolon after endl, or remove the second cout. You should put in a final endl or '\n' too... on some systems you won't be able to read the output otherwise (as the shell prompt will return to the left-of-screen then overwrite it).
You probably don't want this bit:
cout<<sizeof(a)<<endl<<cout<<sizeof(b);
^^^^^^
Older implementations of streams had an operator void*(), to allow constructs like if (cout) without allowing implicit conversions to bool and other numeric types; you are seeing the result of that, concatenated with the final value. A C++11 implementation should have an explicit operator bool() insead, and so should cause a compile error here.
Removing that gives something like:
0x28ff2e
0x28ff10
2
3
as you would expect.
"the result of this I am puzzled"
cout< < sizeof(a)< <endl << cout <<sizeof(b);
^^^ The "puzzling" address comes from this
Remove it and see the result
cout output to standard output is implementation defined
You have a stray cout there. Note that you're effectively printing cout into cout here:
cout << ... << cout << sizeof(b);
cout needs some form of conversion to boolean. Before C++11, this was provided by a conversion to void*; this happens in your case, as the only way cout can be converted to something streamable. Note that there's an extra 3 after 6 hexa digits of the pointer - that's the 3 produced by sizeof(b)

This program should give the AND of the following numbers. What does this mean?

For an assignment in my C++ programming class, I was given the following code. The assignment simply says "This program should give the AND of the following numbers" Was wondering if could get clarification on the meaning. I have an idea but I think I still need a bit of advice. The code was provided jumbled on purpose which I had to clear up. Here is is cleaned up:
// Question2
// This program should give the AND of the inputted numbers.
#include <iostream>
//**Needs namespace statement to directly access cin and cout without using std::
using namespace std;
//**Divided up statements that are running together for better readability
//**Used more spacing in between characters and lines to further increase readability
////void main()
//**Main function should include int as datatype; main is not typically defined as a void function
int main()
{
int i;
int k;
//**Changed spacing to properly enclose entire string
cout << "Enter 0 (false) or 1 (true) for the first value: " << endl;
cin >> i;
cout<< "Enter 0 (false) or 1 (true) for the second value: " << endl;
cin >> k;
//**Spaced out characters and separated couts by lines
//**to help with readability
cout << "AND" << endl;
cout << "k\t| 0\t| 1" << endl;
cout << "---\t| ---\t| ---" << endl;
cout << "0\t| 0\t| 0" << endl;
cout << "1\t| 0\t| 1" << endl;
if(i==1&k==1)
cout <<"Result is TRUE" << endl;
else cout << "Result is FALSE" <<endl;
//**Main function typically includes return statement of 0 to end program execution
return 0;
}
Every number has a binary representation. They're asking for the logical and of the bits. Look up the & operator.
'&' is a bitwise and, which means it takes the binary representation of two numbers and compares each bit in the first number against the bit in the same position on the second. If both are 1, the resultant bit in the same position in the output number is 1, otherwise the bit is zero. if (i&k) would have the same result (assuming the input was always 0 or 1), but anyway your if statement compares whether the first bit is 0 or 1, and if both are 1 returns one.
the AND gate(output) will be true only if both inputs are true(1)
true if i==1 && k==1
false if i==0 && k==0,i==1 && k==0,i==0 && k==1.

Unexpected result when looping chars in C++

I'm using the book "Programming Principles and Practice using C++" to learn programming and one of the exercises is looping through the characters a-z using a while-loop.
Now, I have programmed with C++ and other languages before, so I decided to try to use as few lines as possible (while still using a while-loop). However, this came with the cost of my output being kind of messed up.
Code:
#include <iostream>
int main(){
char ch = 'a';
while(ch <= 'z')
std::cout << ch << '\t' << (int) ch++ << std::endl;
return 0;
}
Output:
b 97
c 98
d 99
e 100
...
x 119
y 120
z 121
{ 122
Now I do realize that this could've been done with a for-loop instead, and I did that as well (it worked). But I still don't get what's wrong with this code, and it's really annoying me.
It appears as if I've told it to output "ch+1", since it prints out 'b' where it should print 'a'. The incrementing isn't done until after the integer value of ch has been put into the out-stream (post-increment). And even if I had incremented it earlier, at least the printed characters and their integer values should correspond.
Any ideas of why this code isn't working?
The order of the operator<< calls is well-specified, but the order in which their operands is evaluated is not.
The increment of ch may happen before or after you output ch "the first time", and merely running this program is Undefined anyway because of the interleaved read/write operations:
[2003: 1.9/12]: A full-expression is an expression that is not a
subexpression of another expression. [..]
[2003: 1.9/16]: There is a sequence point at the completion of
evaluation of each full-expression.
[2003: 5/4]: Except where noted, the order of evaluation of operands
of individual operators and subexpressions of individual expressions,
and the order in which side effects take place, is unspecified.
Between the previous and next sequence point a scalar object shall
have its stored value modified at most once by the evaluation of an
expression. Furthermore, the prior value shall be accessed only to
determine the value to be stored. The requirements of this paragraph
shall be met for each allowable ordering of the subexpressions of a
full expression; otherwise the behavior is undefined.
Instead, be explicit:
std::cout << ch << '\t' << int(ch) << std::endl;
++ch;
Your compiler should have warned you about your code. That it didn't indicates that you do not have your diagnostics set at a useful level.
With GCC, use -Wall -Wextra -std=c++98 -pedantic (or -Wall -Wextra -std=c++0x -pedantic for C++0x).
Short answer is that you have a bit of Undefined Behavior because you're both modifying and using the value of the variable ch, via separate sub-expressions, in the same expression.
The Right Thing(TM) to do here is to use the most practical loop for the task at hand:
#include <iostream>
int main(){
for(char ch = 'a'; ch <= 'z'; ++a){
std::cout << ch << '\t' << ch+0 << std::endl;
}
}
The ch++ in your code gets evaluated first. A more readable and correct version would be:
#include <iostream>
int main(){
char ch = 'a';
while(ch <= 'z') {
std::cout << ch << '\t' << int(ch) << std::endl;
++ch;
}
return 0;
}
When you use one variable twice in one command or expression, once with ++ (or --) and once without, you get undefined behavour.
Instead use:
while(ch <= 'z')
{
std::cout << ch << '\t' << (int) ch << std::endl;
ch++;
}