So I have this very simple code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int main()
{
char p[1010];
int b;
while (scanf("%d", &b) != EOF && b)
{
getchar();
scanf("%s", p);
int length = strlen(p);
long long m;
scanf("%ld", &m);
std::cout << m << std::endl;
printf("%ld\n", m);
}
return 0;
}
|
It is meant for inputs like:
b [string p] m
In other words a sample input could be:
The problem is it's not reading the 3rd part, m, correctly. If I feed it the sample input, the output is:
1 2
|
-3689348818177884050
110
|
So cout displays m as being -3689348818177884050 (I've gone through the program with the debugger and that is indeed the real value of m. However prinf displays it as being 110. The weird thing is that if I declare m as global or if I initialize m or if I declare "static long long m", the program works fine. Could anybody explain to me why this is? Why does scanf mess up on an unitialized local variable? And if so why does it work for b?.. since b is unitialized as well..
EDIT: I am using Visual Studio 2010, but GCC (from codeBlocks) provides the same kind of result. Except m won't be -3689348818177884050, but some other random number. Also, I've tried putting a getchar() before the scan but still no change. I've also tried changing the format string of scanf to " %ld" or "%ld ".