2. Reading a String as Input from the Terminal in C
scanf()
Syntax: scanf("%s", str);
● Description: Reads a word or sequence of characters (no spaces).
● Drawbacks: Stops input at whitespace, doesn't handle spaces.
gets() (Deprecated)
Syntax: gets(str);
● Description:
Reads an entire
line including
spaces until
newline.
● Drawbacks:
3. fgets()
Syntax: fgets(str, sizeof(str), stdin);
● Description: Safely reads a line, including spaces, and can handle buffer
size.
● Benefits: Prevents buffer overflow.
● Drawbacks: Includes the newline character at the end of the string.
getchar() (Character by Character)
Syntax:
char ch;
ch = getchar();
● Description: Reads input one
character at a time.
● Benefits: Allows character-level
control.
● Drawbacks: Inefficient for
longer strings.
4. Comparison:
● scanf(): Fast, but stops at whitespace.
● fgets(): Safe for large strings and includes spaces.
● getchar(): Useful for reading character-by-
character.
● gets(): Avoid using, deprecated due to security
risks.
5. Suppressing Input in scanf()
Command
Purpose: To skip certain parts of the input or suppress values that do not need
to be stored.
How to Suppress Input: Use * (asterisk) in the scanf() format specifier to
suppress input without assigning it to a variable.
Syntax:
scanf("format_specifier", &variable);
scanf("%*format_specifier", ...); // Suppresses input
Example 1: Suppressing a Specific Input
int age;
scanf("%*s %d", &age);
● Input: John 25
● Explanation:
○ The %*s skips the string (John).
○ Only the integer (25) is stored in age.
6. Example 2: Ignoring Multiple Inputs
scanf("%*d %*d %d", &num);
● Input: 12 34 56
● Explanation:
○ The first two integers are ignored (12 and 34).
○ Only the third integer (56) is stored in num.
Common Use Cases:
● Ignoring unwanted data in the input.
● Parsing specific fields while ignoring others in formatted input.
Key Points:
● * in scanf(): The asterisk suppresses input, preventing storage.
● Useful when you want to skip certain data without needing to assign
it to a variable.
7. Suppressing Input Using Scanset in scanf()
A scanset is a set of characters specified within square brackets [] that scanf()
can use to control what characters to accept or ignore during input.
Syntax: scanf("%[character_set]", variable);
● Reads only the characters specified in the scanset.
To Suppress Input Using Scanset, add the * modifier:
scanf("%*[character_set]");
Example: Suppressing Vowels
char str[100];
scanf("%*[aeiou] %s", str);
● Input: aeiou Hello
● Explanation:
○ %*[aeiou]: Skips any vowels at the start of the input.
○ %s: Reads the next word (Hello) and stores it in str.
8. Example 2: Suppressing Digits
char name[50];
scanf("%*[0-9] %s", name);
● Input: 12345 John
● Explanation:
○ %*[0-9]: Skips any digits at the start of the input.
○ %s: Reads the word (John) and stores it in name.
Key Points:
● Scanset allows specifying character sets to read or skip.
● Suppress Input with *: Add * before the scanset to skip those
characters.
● Useful for skipping unwanted characters while parsing structured
input.
9. sscanf() Function in
C
Syntax: int sscanf(const char *str, const char *format, ...);
Description:
● The sscanf() function reads formatted input from a string rather than standard input (like
scanf()).
● It parses the string according to the specified format and stores the values in
corresponding variables.
Parameters:
1. str: The input string from which data is extracted.
2. format: A format string containing specifiers to indicate the type of input (e.g., %d for
integers, %s
for strings).
3. ...: The list of variables where the extracted data will be stored.
Return Value:
● Returns the number of input items successfully matched and assigned.
● Returns EOF if an error occurs or if the end of the string is reached before any values
10. Example:
char str[] = "42 Hello";
int num;
char word[20];
sscanf(str, "%d %s", &num, word);
printf("Number: %dn", num);
printf("Word: %sn", word);
Key Points:
// Output: Number: 42
// Output: Word: Hello
● sscanf() reads data from a string instead of standard input
(terminal).
● It’s useful for parsing structured data in strings.
● The format specifiers are the same as scanf().
12. Writing Strings
printf() Function
Syntax: int printf(const char *format, ...);
Description:
● The printf() function prints formatted output to the terminal.
● The format string specifies how the data should be displayed, with placeholders for
variables.
Common Format Specifiers:
● %d – Integer
● %f – Floating-point number
● %c – Character
● %s – String
13. puts()
Function
Syntax:
int puts(const char *str);
Description:
● The puts() function prints a string followed by a newline character to the
terminal.
● It automatically appends a newline (n) at the end.
Example:
puts("Hello, World!"); // Output: Hello, World!n
Advantages:
● Simpler than printf() for printing strings.
● Automatically adds a newline.
Return Value:
● Returns a non-negative value on success.
● Returns EOF on error.
14. putchar()
Function
Syntax:
int putchar(int char);
Description:
● The putchar() function prints a single character to the
terminal.
Example:
putchar('A'); // Output: A
putchar('n'); // Output: (newline)
Return Value:
● Returns the character written as an unsigned
char.
● Returns EOF on error.
15. Comparison of Functions:
● printf(): Flexible, prints formatted output (multiple
types).
● puts(): Simplified for strings, appends newline.
● putchar(): Used for printing single characters.
16. Strlen function
Syntax: size_t strlen(const char *str);
Description: Returns the length of the string str, excluding the null terminator
(0).
Example: char str[] = "Hello, World!";
printf("Length: %zu", strlen(str)); // Output: 13
Benefits:
● Simple to use for finding string length.
● Efficient as it only traverses the string once.
Drawbacks:
● Requires a null-terminated string.
● Cannot detect the size of arrays, only the number of
characters before 0.
17. strcpy – String Copy
Function
Syntax:
char *strcpy(char *dest, const char *src);
Description: Copies the string src into dest. The destination must have enough
space to hold the source string, including the null terminator.
Example:
char src[] = "Copy me";
char dest[20];
strcpy(dest, src);
printf("%s",
dest); // Output:
Copy me
Drawbacks: No bounds
18. strcmp – String Comparison
Function
Syntax:
int strcmp(const char *str1, const char *str2);
Description: Compares two strings lexicographically. Returns:
● 0 if both strings are equal.
● A negative value if str1 is less than str2.
● A positive value if str1 is greater than str2.
Example:
char str1[] = "apple";
char str2[] = "banana";
int result =
strcmp(str1, str2); //
Output: negative value
Benefits:
● Useful for string
comparison in sorting
19. strcat – String Concatenation Function
Syntax: char *strcat(char *dest, const char *src);
● Description: Appends the src string to the dest string, overwriting the null character at
the end of dest.
Example:
char dest[20] = "Hello";
strcat(dest, " World");
printf("%s", dest); // Output: Hello World
● Benefits: Simple string concatenation.
● Drawbacks: No bounds checking; can cause buffer overflow if dest is not large enough.
20. strncat – Safe String Concatenation
Syntax: char *strncat(char *dest, const char *src, size_t n);
Description: Appends at most n characters from src to dest, ensuring a null
terminator.
Example:
char dest[20] = "Hello";
strncat(dest, " World", 3);
printf("%s", dest); // Output: Hello Wo
Benefits: Adds a layer of safety by limiting the
number of characters appended.
Drawbacks: Still requires care with buffer sizes.
21. strchr – String Character Search
Syntax: char *strchr(const char *str, int c);
Description: Searches for the first occurrence of the character c in the string str
and returns a pointer to it, or NULL if not found.
Example:
char str[] = "Find me!";
char *ptr = strchr(str, 'm');
printf("%s", ptr); // Output: me!
Benefits: Fast character search within
strings.
Drawbacks: Returns NULL if the character is not found, which can lead to null
pointer dereferencing if unchecked.
22. strstr – Substring Search
Syntax: char *strstr(const char *haystack, const char *needle);
Description: Finds the first occurrence of the substring needle in the string haystack
and returns a pointer to it, or NULL if not found.
Example:
char str[] = "Find the needle in the haystack";
char *ptr = strstr(str, "needle");
printf("%s", ptr); // Output: needle in the haystack
Benefits: Useful for substring searches.
Drawbacks: Case-sensitive; returns NULL if no match is found.
23. 1. Write a program to read the names of n students of a class.
2. Write a program to sort names of students.
3. Write a program to read a sentence. Then count the number of words
in the sentence
4. Write a program to enter a text that contains multiple lines. Display the n
lines of text starting from the mth line.
25. Answer:
Error: Strings in C cannot be assigned using the = operator. This will result in a compilation error because
arrays cannot be directly assigned.
Fix: Use strcpy() from the <string.h> library to copy strings.
Corrected Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[10] = "Hello";
char str2[10];
strcpy(str2, str1); // Use strcpy to copy
strings printf("String 2: %sn", str2);
return 0;
}
27. Error: The size of str is too small to handle user input. If the user enters more than 4 characters, it will
cause buffer overflow.
Fix: Either increase the size of the array, or limit the number of characters to be read using %Ns where
N is the maximum number of characters.
Corrected Code:
#include <stdio.h>
int main() {
char str[100]; // Increase buffer size
printf("Enter a string: ");
scanf("%99s", str); // Limit input to prevent
overflow printf("You entered: %sn", str);
return 0;
}
29. Error:
● String literals are stored in read-only memory in most systems, so modifying them results in undefined
behavior.
Fix:
● Use an array to store the string if you need to modify it.
30. #include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] =
"World"; if (str1 ==
str2) {
printf("Strings
are equaln");
} else {
printf("Strings
are not equaln");
}
return 0;
}
31. Error:
● You cannot compare strings using == in C. This compares the
addresses of the strings, not the content.
Fix:
● Use the strcmp() function from the <string.h> library to
compare the content of the strings.
33. Error:
● The size of str is too small. The string "Hello" has 5 characters,
but C strings require an additional byte for the null terminator (0).
Fix:
● Increase the size of the array to accommodate the null terminator.
35. Error:
● Index 5 in the string "Hello" is the null terminator (0). It is technically valid but may not produce the expected
output.
Fix:
● If you want to print the last character, use index 4.
37. Error: If the user enters a string with spaces, scanf() will stop reading
at the first space, so only the first word will be stored.
Fix: Use fgets() to read the entire line, including spaces.
38. Find the error in the following codes:
#include <stdio.h>
int main()
{ char
str[10];
gets(str); // Input string
printf("You entered: %sn",
str); return 0;
}
39. Answer:
Error:
● The function gets() is dangerous and should not be used because it
does not perform bounds checking, leading to potential buffer
overflow.
Fix:
● Use fgets() instead of gets() to avoid buffer overflow.