#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS
int main(void){
//declare 3 char arrays to hold 3 strings of 20 characters each.
char string1[51];
char string2[51];
char string3[51];
// Prompt the user to enter string 1.
printf("Input String 1 : ");
/* Use the gets() function to input the string user enters into string1*/
fgets(string1, sizeof(string1), stdin);
// Prompt the user to enter string 2.
printf("Input String 2 : ");
/* Use the gets() function to input the string user enters into string2*/
fgets(string2, sizeof(string2), stdin);
//Perform the strcpy() operation on string3 from string 1.
//char *strcpy(char *string3, const char *string1);
//strcpy_s(string3, string1, sizeof(string3) - 1);
memcpy(string3, string1, 51);
//print string 3
printf("String3: ");
printf("%s",string3);
//Use the strlen() function on string 2
int len;
len = strlen(string2);
//print the output.
printf("String 2 length: ");
printf("%d \n",len);
//Use the strcmp function to compare string and string 2.
int results;
strcmp(string1, string2);
results = strcmp(string1, string2);
//print the result
if (results < 0) {
printf("str1 is less than str2\n");
}
else if (results > 0) {
printf("str2 is less than str1\n");
}
else {
printf("str1 is equal to str2\n");
}
//Convert characters in string 1 to uppercase using the toupper()
int i = 0;
int j = 0;
char chr;
for (i = 0; string1[i]; i++)
{
chr = string1[i];
printf("%c", toupper(chr));
}
/*Convert all the characters in string 2 to uppercase using the tolower()
function on every character using a for loop.*/
for (j = 0; string2[i]; j++)
{
chr = string2[i];
printf("%c", tolower(chr));
}
return 0;
}
I am trying to copy string1 to string3, but when I use strcpy()
or strcpy_s()
it throws an error. If I completely remove strcpy()
from the program it will run.
I am inputting 50 characters for each string, so do they need to be 51 because of the null?
I have updated my code. I cannot get tolower() to display string2 in lowercase when input uppercase letters.
Please advise me on changes and why they need to be made.
The error: Error C4996 'strcpy': This function or variable may be unsafe.
Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS
That error is due to Visual Studio not liking strcpy
and suggesting to use strcpy_s
, which prevents buffer overruns.
strcpy_s(string3, sizeof(string3), string1);
Please keep in mind that strcpy_s
is only available in a few platforms. strncpy
is a more portable function that does a similar thing, however you will need to pass it sizeof(string3) - 1
instead of sizeof(string3)
and it will not null-terminate the result if all of the 50 bytes of string3
are written, so you will have to do that yourself.
strncpy(string3, string1, sizeof(string3) - 1);
string3[sizeof(string3) - 1] = '\0';
Alternatively, you can #define _CRT_SECURE_NO_WARNINGS
and keep using strcpy
.