Arithmetic expression

Hi, guys.

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>)
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
#include <cstdio>
#include <cctype>
#include <stack>
using namespace 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

1
1



<- // here is the cursor now

I don't understand why it does what it does...

Any ideas?
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:

a
a


_ //cursor here

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:

 
else printf("%c\n",C);
to
 
else if(C != '\n' || C != '\r') printf("%c\n",C);

it should do what you want.
Yup, know I understand and twsouthwick thaks for solution, but unfortunately it's wrong. Correct one is

else if (C != '\n' && C != '\r') printf("%c\n",C);

;-).
Final version.

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
		return true;
	} else
		return false;
}
Topic archived. No new replies allowed.