0
#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.

7
  • 3
    What input are you using? Commented May 30, 2021 at 16:14
  • @Stephen Newell I am providing any character apart form n. Commented May 30, 2021 at 16:31
  • 1
    echo 'an' | ./loop prints it once for me. Commented May 30, 2021 at 16:32
  • coliru.stacked-crooked.com/a/c2789ed81994f370 Commented May 30, 2021 at 16:34
  • 1
    @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. Commented May 30, 2021 at 17:20

2 Answers 2

-1

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"); 
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm pretty sure this will solve your issue. Please mark it as accepted if it helped.
@Siddhant- Your solution printed the hello once but when I gave space before %c as commented by Diogo Vieira also does the same. Need to investigate this behavior.
Actually the space behavior is compiler dependent
-1

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.