#include<stdio.h>
int main(){
    char inputs[33];
    int i;
    for(i;i<33;i++)
    inputs[i]=' ';
    int ch;
    for(i=0;(ch=getchar())!=EOF&&i<32&&ch!='\n';i++)
    {printf("%c",ch);
    inputs[i]=ch;
}

    inputs[i]='\0';

printf("%s",inputs);




    return 0;
}

I am writing a program where the user enters a character and the program stops asking the user for a character when the user enters the Enter key. Enter key is stored in the buffer of getchar as '\n' or '\r'?? Also to echo back the character entered I have used a printf. The problem with the output is that the input is displayed 3 times! I expected two times because of the 2 printf's but I can't understand why 3 times??? Also in the above code in the for loop the ch is assigned the character the user enters THEN it is compared with EOF THEN i is compared and LASTLY ch is compared with '\n'. Do the comparisons occur in the order I specified?? Also, if you reduce the size of the array to say 3 the while loop keeps on looping and asking for characters even when 2 characters are specified and the loop should break because of the i<3 comparison. I also can't figure that one out!!!

Recommended Answers

All 2 Replies

Enter key is stored in the buffer of getchar as '\n' or '\r'??

'\n', always. Even if the underlying representation for the system is different (such as CRLF on Windows), getchar() will convert a newline to '\n' for you. That works for output too, so '\n' will become the system's newline sequence.

The problem with the output is that the input is displayed 3 times! I expected two times because of the 2 printf's but I can't understand why 3 times???

You'll need to say exactly what the input is for me to be sure, but I suspect you're confusing the echo of typing the characters with the actual output from printf().

Do the comparisons occur in the order I specified??

Yes. Further, because of the short circuiting behavior of the && operator, it's guaranteed that the sequence of tests will end on the first comparison that fails. So if getchar() returns EOF, i won't be tested for 32 and ch won't be tested for '\n'. If getchar() succeeds but i is 32, ch won't be tested against '\n'.

Also, if you reduce the size of the array to say 3 the while loop keeps on looping and asking for characters even when 2 characters are specified and the loop should break because of the i<3 comparison. I also can't figure that one out!!!

It's hard to guess without seeing an example.

Hey once again thanks alot..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.