通过 %c 和 %s 将字符串作为用户输入并确认两个字符串相等
Take string as input from user by %c and %s and confirm that both the strings are equal
#include <stdio.h>
#include <string.h>
int main() {
char str1[20];
char *str2;
printf("enter string \n"); **// using %c input**
scanf("%c",str1);
printf(" string 1 is %s \n",str1);
printf("enter string 2 \n");
scanf("%s",*str2); //using %s input
printf(" string 1 and 2 is %c and %s \n",str1,str2);**strong text**
int a=strcmp(str1,str2); //**comparing both**
printf("%d",a);
return 0;
}
使用 %c 和 %s 从用户那里获取输入
然后使用 strcmp 比较字符串的相等性
%c
读取一个字符并且不添加终止空字符,因此您必须添加它才能将数据用作字符串。
- 在读取那里的内容之前,必须分配缓冲区并分配给
str2
。
%s
in scanf()
需要一个指针char*
,所以应该传递str2
而不是*str2
。
%c
in printf()
需要int
,而不是char*
,所以你必须尊重指针(自动从数组转换而来)。
试试这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char str1[20];
char *str2;
printf("enter string \n"); // **using %c input**
scanf("%c",str1);
str1[1] = '[=10=]'; // add terminating null-charachter
printf(" string 1 is %s \n",str1);
str2 = malloc(102400); // allocate buffer
if (str2 == NULL) return 1; // check if allocation is successful
printf("enter string 2 \n");
// pass correct thing
scanf("%s",str2); //using %s input
printf(" string 1 and 2 is %c and %s \n",*str1,str2); // pass correct thing for %c
int a=strcmp(str1,str2); //**comparing both**
printf("%d",a);
free(str2); // free the allocated buffer
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str1[20];
char *str2;
printf("enter string \n"); **// using %c input**
scanf("%c",str1);
printf(" string 1 is %s \n",str1);
printf("enter string 2 \n");
scanf("%s",*str2); //using %s input
printf(" string 1 and 2 is %c and %s \n",str1,str2);**strong text**
int a=strcmp(str1,str2); //**comparing both**
printf("%d",a);
return 0;
}
使用 %c 和 %s 从用户那里获取输入 然后使用 strcmp 比较字符串的相等性
%c
读取一个字符并且不添加终止空字符,因此您必须添加它才能将数据用作字符串。- 在读取那里的内容之前,必须分配缓冲区并分配给
str2
。 %s
inscanf()
需要一个指针char*
,所以应该传递str2
而不是*str2
。%c
inprintf()
需要int
,而不是char*
,所以你必须尊重指针(自动从数组转换而来)。
试试这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char str1[20];
char *str2;
printf("enter string \n"); // **using %c input**
scanf("%c",str1);
str1[1] = '[=10=]'; // add terminating null-charachter
printf(" string 1 is %s \n",str1);
str2 = malloc(102400); // allocate buffer
if (str2 == NULL) return 1; // check if allocation is successful
printf("enter string 2 \n");
// pass correct thing
scanf("%s",str2); //using %s input
printf(" string 1 and 2 is %c and %s \n",*str1,str2); // pass correct thing for %c
int a=strcmp(str1,str2); //**comparing both**
printf("%d",a);
free(str2); // free the allocated buffer
return 0;
}