Introduction
In C programming, the string.h library provides several functions for manipulating strings. This blog post will explore the usage of string manipulation functions in C, along with a detailed explanation of user input using scanf and fgets. We will analyze a code snippet that showcases these concepts and discuss each aspect of the code step by step.
Code Snippet
Including string.h
The first line of the code snippet #include <string.h> is a preprocessor directive that includes the string.h header file. This file contains function declarations for string manipulation, such as strlen, strcpy, strcat, and strcmp. By including this header file, we gain access to these functions, which we will utilize in the code snippet.
Creating a Directory
To begin, let's create a file named intermediate.c using the command line. Follow the instructions below based on your operating system:
- Open the command prompt or PowerShell.
- Run the following commands:
cd basic-programming/c-programming
- Open the file in your favorite text editor.
code intermediate.c
or
vim intermediate.c # installed by default on macOS
or
emacs -Q -nw intermediate.c
or
nano intermediate.c # installed by default on Linux
Note:
Make sure you save changes in the file.
String Manipulation using string.h Functions
In this section, we'll analyze the code related to string manipulation functions provided by the string.h library.
// String Manipulation
strcat(firstText, secondText);
strcpy(secondStr, thirdStr);
const int str13Cmp = strcmp(firstStr, thirdStr);
const int str3greetingCmp = strcmp(thirdStr, greeting);
In the code above, we perform various string manipulation operations:
strcat(firstText, secondText);: This line uses thestrcatfunction to concatenate thesecondTextstring at the end of thefirstTextstring. The result is that thefirstTextstring becomes "Hello World!".strcpy(secondStr, thirdStr);: Here, we use thestrcpyfunction to copy the contents of thethirdStrstring into thesecondStrarray. This operation creates an independent copy of the string.const int str13Cmp = strcmp(firstStr, thirdStr);: Thestrcmpfunction compares the contents of thefirstStrandthirdStrstrings. It returns an integer value indicating the result of the comparison. If the two strings are equal, it returns 0. IffirstStris lexicographically less thanthirdStr, it returns a negative value. IffirstStris lexicographically greater thanthirdStr, it returns a positive value. The result is stored in thestr13Cmpvariable.const int str3greetingCmp = strcmp(thirdStr, greeting);: Similarly, this line compares thethirdStrandgreetingstrings usingstrcmpand stores the result in thestr3greetingCmpvariable.
User Input using scanf
Now, let's look at the code related to user input using the scanf function.
// User Input using scanf
printf("Please type your age and grade: ");
scanf("%d %c", &myAge, &myChar);
printf("Please enter your first name: ");
scanf("%19s", myFirstName);
In the code above, we use scanf to retrieve user input:
scanf("%d %c", &myAge, &myChar);: This line prompts the user to enter their age and grade. The format string"%d %c"specifies that we expect an integer followed by a character as input. The&operator is used to pass the memory addresses ofmyAgeandmyCharvariables to store the values entered by the user.scanf("%19s", myFirstName);: This line prompts the user to enter their first name. The format string"%19s"specifies that we expect a string input with a maximum length of 19 characters (to avoid buffer overflow). The entered string is stored in themyFirstNamecharacter array.
User Input using fgets
Here's the code that demonstrates user input using the fgets function.
// User Input using fgets
printf("Please enter your full name: ");
getchar(); // Clear the newline character from the previous input
fgets(myFullName, sizeof(myFullName), stdin);
myFullName[strcspn(myFullName, "\n")] = '\0';
In the code above, we utilize fgets to obtain user input:
fgets(myFullName, sizeof(myFullName), stdin);: This line reads a line of input from the user, storing it in themyFullNamecharacter array. Thesizeof(myFullName)argument specifies the maximum number of characters to read, preventing buffer overflow. Thestdinstream indicates that the input is read from the standard input (keyboard).myFullName[strcspn(myFullName, "\n")] = '\0';: Sincefgetscaptures the newline character (\n) when the user presses Enter, this line removes the newline character from themyFullNamestring by replacing it with a null character (\0). This step ensures that the string ends at the intended input and doesn't include the newline character.
Memory Address and Pointers
This section focuses on memory addresses and pointers used in the code.
// Memory Address and Pointers
printf("My age is: %d\n", myAge);
printf("My character is: %c\n", myChar);
printf("My first name is: %s\n", myFirstName);
printf("My full name is: %s\n", myFullName);
printf("%p\n", (void*)&myAge);
printf("%p\n", (void*)ptr);
printf("%d\n", *ptr);
In the code above, we work with memory addresses and pointers:
printf("My age is: %d\n", myAge);: This line displays the value of themyAgevariable, representing the age entered by the user.printf("My character is: %c\n", myChar);: Here, we print the value of themyCharvariable, which corresponds to the grade entered by the user.printf("My first name is: %s\n", myFirstName);: This line outputs the contents of themyFirstNamecharacter array, which contains the user's first name.printf("My full name is: %s\n", myFullName);: Similarly, we display the content of themyFullNamecharacter array, which holds the user's full name.printf("%p\n", (void*)&myAge);: This line prints the memory address of themyAgevariable using the%pformat specifier. The&operator retrieves the address of the variable.printf("%p\n", (void*)ptr);: Here, we print the memory address stored in theptrpointer variable. The(void*)cast is used to ensure proper formatting of the memory address.printf("%d\n", *ptr);: This line dereferences theptrpointer and prints the value stored at the memory address it points to. Sinceptrpoints tomyAge, it effectively displays the value ofmyAge.
Output
Finally, the code snippet includes several printf statements to display the output.
// Output
printf("%d\n", alphabetLength);
printf("%d\n", alphabetByte);
printf("%s\n", firstText);
printf("%s\n", secondStr);
printf("%d\n", str13Cmp);
printf("%d\n", str3greetingCmp);
The code above produces the following output:
alphabetLength: This line prints the length of thealphabetstring, which is determined using thestrlenfunction.alphabetByte: Similarly, this line displays the size (in bytes) of thealphabetarray, obtained using thesizeofoperator.firstText: This line outputs the contents of thefirstTextcharacter array, which now contains the concatenated string "Hello World!".secondStr: Here, we print the contents of thesecondStrcharacter array, which was assigned the value of thethirdStrstring usingstrcpy.str13Cmp: This line displays the result of comparing thefirstStrandthirdStrstrings usingstrcmp. It indicates whether the two strings are equal or different.str3greetingCmp: Similarly, this line shows the result of comparing thethirdStrandgreetingstrings usingstrcmp.
Practive
Assuming you have an account or are already logged in on Replit.
- Try the Replit Editor online.
- Click the Fork button.
- Edit the current code.
Conclusion
In this blog post, we explored the usage of string manipulation functions provided by the string.h library in C programming. We discussed functions such as strlen, strcpy, strcat, and strcmp, along with their purpose and how they are utilized in the code snippet. Additionally, we examined user input using scanf and fgets, which allow the program to receive input from the user. Finally, we covered memory addresses and pointers, highlighting their significance and demonstrating their usage in the code snippet.
References
String and Character Array
Introduction to C Pointers
Using Pointers in C
What is return type of getchar(), fgetc() and getc()?
Top comments (0)