C User Input

1. Basic Input Functions

In C, user input is mainly taken using:

  1. scanf() → Reads formatted input

  2. getchar() → Reads a single character

  3. gets() → Reads a string (unsafe, avoid using)

  4. fgets() → Reads a string safely


2. Using scanf()

  • scanf() is used for numbers, characters, and strings.

  • Always provide address of the variable using & for non-string types.

Syntax:



 

Example 1: Read an integer


 

Input/Output:

Enter your age: 25
You are 25 years old.

Example 2: Read a float

#include <stdio.h>

int main() {
float price;
printf(“Enter price: “);
scanf(“%f”, &price);
printf(“Price = %.2f\n”, price);
return 0;
}

Input/Output:

Enter price: 99.5
Price = 99.50

Example 3: Read a character

#include <stdio.h>

int main() {
char grade;
printf(“Enter your grade: “);
scanf(” %c”, &grade); // note the space before %c
printf(“Your grade: %c\n”, grade);
return 0;
}

Input/Output:

Enter your grade: A
Your grade: A

Tip: Space before %c in scanf ignores previous newline character.


Example 4: Read a string

#include <stdio.h>

int main() {
char name[50];
printf(“Enter your name: “);
scanf(“%s”, name); // stops at space
printf(“Hello, %s!\n”, name);
return 0;
}

Input/Output:

Enter your name: Alice
Hello, Alice!

Note: scanf("%s") cannot read strings with spaces.


3. Using fgets() for Strings with Spaces

#include <stdio.h>

int main() {
char name[50];
printf(“Enter your full name: “);
fgets(name, sizeof(name), stdin); // reads spaces
printf(“Hello, %s”, name); // fgets keeps newline
return 0;
}

Input/Output:

Enter your full name: Alice Johnson
Hello, Alice Johnson

Use strcspn(name, "\n") to remove the newline if needed:

name[strcspn(name, "\n")] = '\0';

4. Using getchar() to Read Single Character

#include <stdio.h>

int main() {
char ch;
printf(“Press any key: “);
ch = getchar();
printf(“You pressed: %c\n”, ch);
return 0;
}

Input/Output:

Press any key: A
You pressed: A

5. Key Points About User Input

  1. Use scanf for formatted input (numbers, strings without spaces, chars).

  2. Use fgets for strings with spaces.

  3. Use getchar for single characters.

  4. Always check array size for strings to avoid buffer overflow.

  5. Use & with variables except strings, because strings are already pointers.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *