Back to C Programming
2026-07-145 min read

String Input (C Programming)

Learn String Input (C Programming) step by step with clear examples and exercises.

Why This Matters

In C programming, understanding how to take user input as a string is crucial for creating interactive applications. It allows you to gather data from users, which is essential for various scenarios such as taking command-line arguments, gathering user preferences, and even building simple text-based games. Mastering string input can also help prepare you for coding interviews and real-world programming challenges.

Prerequisites

Before diving into string input, it's important to have a solid understanding of the following concepts:

  1. C basics: variables, data types, operators, control structures (if statements, loops)
  2. Input/Output functions: scanf() and printf()
  3. Arrays: one-dimensional arrays and multi-dimensional arrays
  4. Pointers: understanding how pointers work and how to manipulate them
  5. Basic file I/O: fopen, fclose, fgets, and fprintf functions

Core Concept

To take user input as a string in C, we use the scanf() function along with the format specifier %s. However, it's essential to understand that scanf() can lead to buffer overflow vulnerabilities if not used carefully. To avoid this issue, always ensure that the input length does not exceed the allocated array size and consider using safer alternatives such as fgets().

Here's a simple example of how to take user input as a string:

#include <stdio.h>

int main() {
char str[100]; // Allocate memory for 100 characters

printf("Enter your name: ");
fgets(str, sizeof(str), stdin); // Read user input into the string 'str' safely

printf("Hello, %s! Welcome to C programming.\n", str);

return 0;
}

In this example, we first declare a character array str with a size of 100 elements. Then, we use the fgets() function to prompt the user for their name and read the input into the str array safely. The sizeof(str) argument ensures that the input does not exceed the array's capacity, preventing potential buffer overflow vulnerabilities. Finally, we print a greeting message using the user's input.

Worked Example

Let's consider a more complex example where we take two strings as input, perform some operations on them, and then output the result:

#include <stdio.h>
#include <string.h> // Include string manipulation functions

int main() {
char str1[50], str2[50]; // Allocate memory for 50 characters each
int len1, len2; // Store lengths of the strings

printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin); // Read user input into 'str1' safely

printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin); // Read user input into 'str2' safely

len1 = strlen(str1); // Calculate length of the first string
len2 = strlen(str2); // Calculate length of the second string

if (len1 > len2) {
printf("First string is longer.\n");
} else if (len1 < len2) {
printf("Second string is longer.\n");
} else {
printf("Both strings have the same length.\n");
}

// Concatenate the two strings and store the result in a new array
char concat[len1 + len2 + 1];
strcpy(concat, str1);
strcat(concat, str2);

printf("Concatenated string: %s\n", concat);

return 0;
}

In this example, we first declare two character arrays str1 and str2 with a size of 50 characters each. We use the fgets() function to safely read user input into both arrays. Then, we calculate the length of each string and compare them to determine which string is longer. Next, we concatenate the two strings using the strcat() function and store the result in a new character array called concat. Finally, we print the concatenated string as our output.

Common Mistakes

  1. Buffer overflow: Failing to check the input length against the allocated array size can lead to buffer overflow vulnerabilities. Always ensure that your input does not exceed the array's capacity.
  2. Incorrect format specifiers: Using incorrect format specifiers with scanf() or printf() can lead to unexpected results or program crashes. Always use the correct format specifier for your data type (e.g., %s for strings, %d for integers).
  3. Forgetting to include necessary header files: Remember to include the appropriate header files (e.g., ` for input/output functions, ` for string manipulation functions).
  4. Ignoring whitespace in input: When reading user input with scanf(), be aware that it will stop at the first whitespace character (space, tab, or newline). To read a whole line of input, use fgets().
  5. Not handling newline characters: After using fgets() to read a line of input, there may still be a newline character left in the input buffer. You can remove it by using strtok() or getchar().
  6. Not checking for string termination: Always check if the user's input has been properly stored in the string array by looking for the null character (\0) at the end of the array.

Practice Questions

  1. Write a program that takes two strings as input and checks if they are anagrams of each other (i.e., the letters in one string can be rearranged to form the other string).
  2. Write a program that counts the number of occurrences of each character in a given string.
  3. Write a program that reverses a given string.
  4. Write a program that sorts an array of strings alphabetically using bubble sort or quicksort algorithm.
  5. Write a program that reads a file line by line and counts the number of words, lines, and characters in the file.
  6. Write a program that takes a string as input, removes all duplicate characters, and stores the result in a new string.
  7. Write a program that finds the longest common substring between two given strings.
  8. Write a program that checks if a given string is a palindrome (reads the same forwards and backwards).
  9. Write a program that implements a simple text editor where users can enter, save, load, and exit the editor.
  10. Write a program that implements a simple calculator with basic arithmetic operations (+, -, *, /) and user input validation.

FAQ

Why is it important to check the length of user input when using scanf()?

Checking the length of user input helps prevent buffer overflow vulnerabilities by ensuring that the input does not exceed the allocated array size.

What are some common mistakes when working with strings in C?

Common mistakes include using incorrect format specifiers, forgetting to include necessary header files, ignoring whitespace in input, not handling newline characters, and not checking for string termination.

Why should I use fgets() instead of scanf() when reading user input as a string?

fgets() is safer than scanf() because it reads the entire line of input up to a specified limit, while scanf() stops at the first whitespace character. This makes fgets() less prone to buffer overflow vulnerabilities and more suitable for reading user input as a string.

How can I remove duplicate characters from a given string in C?

To remove duplicate characters from a given string in C, you can create a new string that only contains unique characters by iterating through the original string and adding each character to the new string only if it has not been encountered before.

What is the difference between strcpy() and strcat() in C?

strcpy() copies the source string (including the null terminator) into the destination string, overwriting any existing data in the destination. strcat() concatenates the source string to the end of the destination string without overwriting the null terminator.