This is a C program that demonstrates the use of the string manipulation functions in the C standard library. The program prompts the user to input a string using the gets()
function and then copies the string into a new character array using the strcpy()
function.
#include <stdio.h>
#include <string.h>
int main()
{
//char some_string[] = "This is some string.";
char some_string[100];
printf("Enter Some String: \n");
gets(some_string);
char target_string[10];
printf("Some String: %s \n", some_string);
printf("Initial Target String: %s \n", target_string);
strcpy(target_string, some_string);
printf("Final Target String: %s \n", target_string);
/*
for (int x = 0; x < strlen(target_string); x++) {
printf("%c \n", target_string[x]);
}
*/
return 0;
}
Result:
Enter Some String:
this is original string
Some String: this is original string
Initial Target String:
Final Target String: this is original string
Process returned 0 (0x0) execution time : 10.649 s
Press any key to continue.
Here's an explanation of each block of code in the program:
#include <stdio.h>
#include <string.h>
These are header files that are included in the program to provide definitions for functions used later in the code. stdio.h
is included for standard input/output functions, while string.h
is included for string manipulation functions.
int main()
{
This is the main function of the program, where execution begins. The function returns an integer value (in this case, 0) to indicate the status of the program when it exits.
char some_string[100];
printf("Enter Some String: \n");
gets(some_string);
This declares a character array called some_string
with a size of 100 and prompts the user to input a string using the gets()
function. The gets()
function reads a line of text from standard input and stores it in the some_string
array. However, as mentioned earlier, using gets()
is not recommended due to potential buffer overflow vulnerabilities.
char target_string[10];
printf("Some String: %s \n", some_string);
printf("Initial Target String: %s \n", target_string);
strcpy(target_string, some_string);
printf("Final Target String: %s \n", target_string);
This declares a new character array called target_string
with a size of 10 and then uses the printf()
function to display the original input string some_string
and an initial value of target_string
on the console.
The strcpy()
function is then used to copy the contents of some_string
into target_string
. This replaces the original contents of target_string
with the input string.
Finally, the program uses printf()
to display the final value of target_string
.
return 0;
}
This statement ends the main()
function and returns the value 0 to indicate successful program execution.
No comments:
Post a Comment