I have this fragment of code that reads arithmetic expressions like 1 + 2 * 3
into integers and characters:
int main() {
int d, flag = 0;
char c;
while ((flag = scanf("%d", &d)) != EOF)
{
if (flag == 1) // if integer was read sucessfully
{
// an integer has been read into variable 'd'
printf("%d,", d);
}
else // else if it was a character
{
// then read char into variable 'c'
c = getchar();
printf("%c,", c);
}
}
}
Now this code works when compiled with MingGW on Windows and MacOS, but somehow on Linux, it characters +
and -
are not read correctly.
Sample run:
Input: 1 * 2 * 3
Output: 1,*,2,*,3,
Input: 1 + 2 - 3
Output: 1, ,2, ,3,
Input: 1 ++ 2 -- 3
Output: 1,+,2,-,3
Somehow the +
and -
characters are read as spaces. But it works if we put double ++
and --
. Again this only happens when compiled on Linux, and on almost all online IDEs. It's puzzling why only the +
and -
character? Could it be they are recognised as positive and negative signs?