+ 1
[check code] : Why does Code 1 prints the characters as it is sent through "scanf" and code 2 doesn't. Please Explain
[check code] : Why does Code 1 prints the characters as it is sent through "scanf" and code 2 doesn't. Please Explain CODE 1 : #include <stdio.h> int main() { char name[100]; int i; char ch; for (i = 0; ch != '\n'; i++) { scanf("%c", &ch); name[i]=ch; } name[i] = '\0'; puts(name); return 0; } input : Anirban Mitra output : Anirban MItra CODE 2 : #include <stdio.h> int main() { char name[100]; int i; for (i = 0; name[i] != '\n'; i++) { scanf("%c", &name[i]); } name[i] = '\0'; puts(name); return 0; } input : Anirban Mitra output : prints nothing.. :/ idk what happens here
3 Respostas
+ 2
hmmm
In first case, you must enter \n character explicitly to stop loop..
It works fine then but you are using
ch != '\n' , in first time you are comparing uninitialized ch so it may behave undefined way some times.. Better to use do-while loop here in these cases..
In 2nd program , also it reading undefined times, so there because of infinite loop, you don't getting no output..
You are reading character into name[i] , after this i++ executes so when you comparing name[i] != '\n' , here name[i] is still undefined, not assigned character variable , it is next location you are going to read, not already read character.
So name[i] != '\n' is always true, never false..
+ 1
Its works.... Just compile again...
0
Please don't tag languages like "java" when this has nothing to do with it.