scanf("%79s%79s", string1, string2);
This solved the problem for me. Or may use:
scanf_s("%79s %79s", string1,80, string2, 80);
سؤال
I have a program that read 2 strings from keyboard and string1 will be replaced by string2. The problem is program crashes right after I press Enter. Can everybody explain what's wrong in my program? Thank you!
#include<stdio.h>
#define SIZE 80
void mystery1( char *s1, const char *s2 );
int main( void)
{
char string1[ SIZE];
char string2[ SIZE ];
puts("Enter two strings: ");
scanf_s("%79s%79s",string1,string2); // this line makes program crashed
mystery1(string1, string2);
printf_s("%s", string1);
}
// What does this function do?
void mystery1(char *s1, const char *s2 )
{
while ( *s1 != '\0') {
++s1;
}
for( ; *s1 = *s2; ++s1, ++s2 ) {
;
}
}
المحلول
scanf("%79s%79s", string1, string2);
This solved the problem for me. Or may use:
scanf_s("%79s %79s", string1,80, string2, 80);
نصائح أخرى
For "What does this function do?", the answer is, it combines both strings into string1
without carrying about overflow.
void mystery1(char *str1, char *str2) {
while(*str1 != '\0') { // Is end of string check
++str1; // Move pointer position to next character.
}
// str1 now points to the first null character of the array.
for(; *str1 = *str2; ++str1, ++str2) {
// Sets the current str1 position to equal str2
// str1 is incremented along with str2, but str1 is starting at the first null character
;
}
}