I'm making a program that will evaluate an arithmetic expression. My algorithm converts the infix representation into postfix first and then proceed to the pure evaluation.
I've started with making a function, which will read a character from the intput, distinguish wheather the character is digit or not and return a character or an integer. It will also return a boolean value wheter the input went right or not.
Here is the code (it's in development, so some stuff may be unused, such as <stack>)
#include <cstdio>
#include <cctype>
#include <stack>
usingnamespace std;
char expression[51];
short ord(char a) { return a-'0'; }
bool readElement(int& value,char& character) {
char C; bool returnValue;
if (scanf("%c",&C) > 0) returnValue = true;
else returnValue = false;
if (isdigit(C)) {
character = '$';
value = ord(C);
} else
character = C;
return returnValue;
}
int main() {
int V; char C;
while (readElement(V,C)) {
if (C == '$') printf("%d\n",V);
else printf("%c\n",C);
}
return 0;
}
Everithing goes right. This is just a test program, which tests wheather it runs properly. As I said, it does. But the thing which bothers me is that for example when I type in input 'a' it prints 'a' on output, but the cursor in console jumps many positions down, Like this
whatever character you put in - you enter it using the <enter> key.
The scanf pick up the char but leaves the <enter> /newline char in the buffer.
You printer the char followed by a new line printf("%c\n",C); so your
console looks like this:
a
a
_ //cursor here
The second time roudf the loop, the scanf picks up the newline char that was left behind in the buffer from the first char - and printf("%c\n",C); ends up printing this newline followed by another new line
so now your console looks like this:
I believe it is because scanf will also include the linefeed when you press enter. On *nix machines, this will be '\n', while in Windows it will be both '\n' and '\r'. If you change the following:
bool readElement(int& value,char& character) {
char c;
do { c = getchar(); } while (c == '\n');
if (c != EOF) {
if (isdigit(c)) {
character = '$';
value = ord(c);
} else
character = c;
returntrue;
} elsereturnfalse;
}