Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What are the input and output for strings in C language?
An array of characters (or) collection of characters is called a string. In C programming, strings are null-terminated character arrays that end with the special character '\0'.
Syntax
// Input functions for strings
scanf("%s", string_name);
fgets(string_name, size, stdin);
// Output functions for strings
printf("%s", string_name);
puts(string_name);
Method 1: Using scanf() and printf()
The scanf() function reads strings until it encounters whitespace, while printf() displays the complete string −
#include <stdio.h>
int main() {
char name[30];
printf("Enter your name: ");
scanf("%s", name);
printf("Your name is: %s<br>", name);
return 0;
}
Enter your name: Lucky Your name is: Lucky
Note: scanf() stops reading at the first space, so it cannot handle names with spaces like "Lucky Lol".
Method 2: Using fgets() and printf()
The fgets() function can read strings with spaces, making it safer than the deprecated gets() function −
#include <stdio.h>
#include <string.h>
int main() {
char name[30];
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin);
/* Remove newline if present */
name[strcspn(name, "<br>")] = '\0';
printf("Your name is: %s<br>", name);
return 0;
}
Enter your full name: Lucky Lol Your name is: Lucky Lol
Key Points
- The '&' operator is not used with string names in
scanf()because the array name represents the base address. -
scanf()stops reading at whitespace, whilefgets()reads entire lines including spaces. - The null terminator '\0' is automatically added by the compiler at the end of strings.
-
fgets()is safer thangets()as it prevents buffer overflow by limiting input size.
Comparison
| Function | Handles Spaces | Safety | Usage |
|---|---|---|---|
| scanf() | No | Moderate | Single words |
| fgets() | Yes | High | Full lines with spaces |
Conclusion
For string input in C, use fgets() for safer input handling, especially when dealing with strings containing spaces. Always ensure proper buffer size management to prevent overflow.
Advertisements
