getchar() to read one character from keyboard

We can use getchar function to read a single character from the keyboard. We will try to take one sample character and display by using printf function. Once the program encounters the getchar() function it will wait for the user to enter data by keyboard. Once it is entered it will be stored in a variable and we can display by using printf function.
#include <stdio.h>
int main(void){
char var;
var = getchar();

printf(" Welcome to  %c",var);
return 0;
}
Using getchar function we can interact with user and execute some conditional statements. WE will ask user if C programming is easy or difficult. Based on the input data we will display a message using one if condition checking.
#include <stdio.h>
int main(void){
char var;
printf( "Do you like C programming ? Press Y or N ");
var = getchar();
  if(var == 'Y')
  {
  printf(" Yes C is very interesting language");
 }
 else
 {
 printf (" Why ? It is easy to learn here, need practice only");
 }
return 0;
}

Example: Reading Multiple Characters

#include <stdio.h>

int main() {
    char ch;
    printf("Enter characters (press q to quit):\n");
    while ((ch = getchar()) != 'q') {
        printf("You entered: %c\n", ch);
    }
    return 0;
}

Example: Handling Whitespace Characters

#include <stdio.h>

int main() {
    char ch;
    printf("Enter text (includes spaces): ");
    while ((ch = getchar()) != '\n') {
        printf("%c", ch);
    }
    return 0;
}

Example 2: Reading Characters in a Loop

This example reads characters from user input until the newline character is entered.

#include <stdio.h>

int main() {
    char ch;
    printf("Enter characters (press Enter to stop):\n");
    
    while ((ch = getchar()) != '\n') {
        printf("You entered: %c\n", ch);
    }
    
    return 0;
}
Output:
Enter characters (press Enter to stop):
H
You entered: H
e
You entered: e
l
You entered: l
l
You entered: l
o
You entered: o
---

Example 3: Pausing Execution with getchar()

This example uses getchar() to pause program execution until the user presses any key.

#include <stdio.h>

int main() {
    printf("Press any key to continue...\n");
    getchar();  // Wait for a key press
    printf("Program continued.\n");
    
    return 0;
}
Output:
Press any key to continue...
Program continued.


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    nurr

    10-11-2013

    hi,
    how i'm going to change this code using string, for example Y change it to YES, and N change it to NO.
    thanks for help...
    Michael Ziile

    22-01-2019

    illustrate with examples
    a)reading character and string variable
    b)writing character and string variable



    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer