C 在字符串中搜索目标字符串
编写一个C程序,读取一系列的字符串,并只打印以字母“ed”结尾的字符串 我的代码:C 在字符串中搜索目标字符串,c,arrays,string,C,Arrays,String,编写一个C程序,读取一系列的字符串,并只打印以字母“ed”结尾的字符串 我的代码: #include<stdio.h> #include<string.h> int main(){ char array[5][10]; int i; for(i=0;i<5;i++){ printf("%s","enter a string");//enter string scanf("%10s",&array[i
#include<stdio.h>
#include<string.h>
int main(){
char array[5][10];
int i;
for(i=0;i<5;i++){
printf("%s","enter a string");//enter string
scanf("%10s",&array[i][0]);
}
char *array[5][0];
for(i=0;i<=4;i++){
length=strlen(array[i][0]);//
if(strcmp((array[i][length-2],"ed")==0) //I wrote to make a comparison//
{
printf("%s\n",&array[i][0]);
}
}
return 0;
}
查看错误消息足以调试代码并使其正常工作。这是非常基本的错误消息,只需读取一次代码即可解决 (一) 错误:同一变量声明了两次。因此,删除一个声明(第14行) (二) 错误:变量
长度
未声明。所以声明它(int-length
)
(三)
很明显,strcmp
需要const char*
,但您给出的是整数<代码>数组[i][length-2]引用字符串中的字符。因此,在strcmp中给出as&数组[i][length-2]
,以给出最后一个元素的地址。与strlen的情况相同。另外,)
不匹配是在if(strcmp((数组[i][length-2],“ed”)==0)
中抛出的参数太少了(和2)
,只需查看代码即可)
(四)
另外,}
程序中存在不匹配
因此,最终在解决错误后,它应该如下所示:
#include <stdio.h>
#include <string.h>
int main()
{
char array[5][10];
int i;
for( i = 0; i < 5; i++ )
{
printf("%s", "enter a string"); //enter string
scanf("%10s", array[i]);
}
for( i = 0; i < 5; i++ )
{
size_t length = strlen(array[i]);
if(strcmp(&array[i][length-2], "ed") == 0)
{
printf("%s\n",array[i]);
}
}
return 0;
}
#包括
#包括
int main()
{
字符数组[5][10];
int i;
对于(i=0;i<5;i++)
{
printf(“%s”,“输入字符串”);//输入字符串
scanf(“%10s”,数组[i]);
}
对于(i=0;i<5;i++)
{
size_t length=strlen(数组[i]);
if(strcmp(&数组[i][length-2],“ed”)==0)
{
printf(“%s\n”,数组[i]);
}
}
返回0;
}
您已经声明了数组
。第二个是另一种类型。对于printf
,不要使用运算符&
的地址。编译器已经传递了地址。删除第二个声明和&
,代码应该会运行…并且有一个(
调用strcmp
“数组”的冲突类型”非常简单。大小\u t长度;
会更好。非常感谢我的代码正在工作:))
extern.c:14:7:conflicting types for ‘array’
char *array[5][0];
^~~~~
extern.c:6:6: note: previous declaration of ‘array’ was here
char array[5][10];
^~~~~
extern.c:16:1: error: ‘length’ undeclared (first use in this function)
length=strlen(array[i][0]);
^~~~~~
extern.c:16:1: note: each undeclared identifier is reported only once for each function it appears in
extern.c:17:11: warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]
if(strcmp((array[i][length-2],"ed")==0)
^
In file included from extern.c:2:0:
/usr/include/string.h:136:12: note: expected ‘const char *’ but argument is of type ‘int’
extern int strcmp (const char *__s1, const char *__s2)
^~~~~~
extern.c:17:4: error: too few arguments to function ‘strcmp’
if(strcmp((array[i][length-2],"ed")==0)
^~~~~~
In file included from extern.c:2:0:
/usr/include/string.h:136:12: note: declared here
extern int strcmp (const char *__s1, const char *__s2)
#include <stdio.h>
#include <string.h>
int main()
{
char array[5][10];
int i;
for( i = 0; i < 5; i++ )
{
printf("%s", "enter a string"); //enter string
scanf("%10s", array[i]);
}
for( i = 0; i < 5; i++ )
{
size_t length = strlen(array[i]);
if(strcmp(&array[i][length-2], "ed") == 0)
{
printf("%s\n",array[i]);
}
}
return 0;
}