0
votes
#include<stdio.h>
 
int main(){
    char ch;
    while(1){
        ch = getchar();
        if(ch =='n'){
            break;
        }
        printf("hello"); 
    }
}

Loop is printing 2 hello's instead of one. while loop is always true and accepts a char from user if the char is n then the loop breaks else it has to print hello and ask for user input again and process. Not able to understand the program behaviour.

2
What input are you using?Stephen Newell
@Stephen Newell I am providing any character apart form n.pranay nallapaneni
echo 'an' | ./loop prints it once for me.Stephen Newell
@pranaynallapaneni How many keys are you hitting? If you hit only 1 key (for example 'a'), the program very likely does nothing. When you hit the second key (for example 'enter' or 'return'), the program reads both of those characters. As written, your program is printing "hello" in response to both the 'a' and the newline.William Pursell

2 Answers

-1
votes

This is happens because when you type a letter, you then press enter, i.e, "\n". Thus, use another getchar() to accommodate that newline character. Ex :-

#include<stdio.h>
 
int main(){
    char ch;
    while(1){
        ch = getchar();
        getchar();
        if(ch =='n'){
            break;
        }
        printf("hello\n"); 
    }
}
-1
votes

getchar() reads exactly one character. If you are entering data interactively and type 1 character followed by a newline, getchar will read 1 characters plus the newline. 1 + 1 = 2, so "hello" is printed twice.

Perhaps you want:

#include <stdio.h>
#include <ctype.h>

int
main(void)
{
        int ch;   /* getchar() returns an int */
        while( (ch = getchar()) != EOF && ch != 'n' ){
                if( ! isspace(ch) ){
                        puts("hello");
                }
        }
        return 0;
}