gpt4 book ai didi

字符比较错误输出并且在C中没有比较

转载 作者:行者123 更新时间:2023-11-30 20:11:20 24 4
gpt4 key购买 nike

C 不比较字符。我已经尝试了很多次,但总是遇到问题。

我的代码是

#include <stdio.h>
#include <string.h>


int main(){
int palavra[16];
int frase[201];
gets(palavra);
gets(frase);
printf("%s\n",palavra);
printf("%s\n",frase);
int i;
int palavrasNaFrase=0;
int tamanhoPalavra=strlen(palavra);
int tamanhoFrase=strlen(frase);
printf("tamanho frase %d\n",tamanhoFrase);
for(i=0; i<tamanhoFrase; i++){
printf("i = %d\n",i);
printf("caracter: %c\n",palavra[0]);
printf("caracter: %c\n",frase[i]);
if(frase[i] == palavra[0]){
printf("C is not comparing characters\n");/*
int j=i+1,k=1;
int letrasIguais=1;
int cont=1;
while(cont<tamanhoPalavra){
if(frase[j]==palavra[k]){
letrasIguais++;
}
j++;
k++;
cont++;
}
if(letrasIguais==tamanhoPalavra){
palavrasNaFrase++;
}*/
}
}
//printf("%d\n",palavrasNaFrase);
return(0);
}

输入

ANA

ANAGOSTADEUMABANANA

ANA

ANAGOSTADEUMABANANA

tamanho frase 19

i = 0

caracter: A

caracter: A

i = 1

caracter: A

caracter: O

i = 2

caracter: A

caracter: D

i = 3

caracter: A

caracter: A

i = 4

caracter: A

caracter: A

C is not comparing characters

i = 5

caracter: A

caracter: ©

i = 6

...

caracter: ­

0

进程返回 0 (0x0) 执行时间:4.696 s按任意键继续。

实在是太麻烦了,不知道该怎么办。请有人帮助我,如果有人能找到问题所在,为什么如此被窃听。有太多错误和不应该发生的事情发生。我已经尝试和搜索了很多次,并且总是找到使用 string[position]==string2[position] 逐个字符比较字符串的方法是正确的,但在这个程序中不起作用,我不知道为什么有这么多错误!请有人帮助我并给我一盏灯!我究竟做错了什么?谢谢

最佳答案

您正在像这样定义数组:

int palavra[16];
int frase[201];

虽然它保留了足够的空间,但在比较 char 与 char 时存在一个问题:比较 int 与 int (多字符与多字符)可能就是您想要的(并且您可能收到关于指针类型的警告你忽略了):

if(frase[i] == palavra[0]){

您必须更改声明以使用 char 代替

char palavra[16];
char frase[201];

编译时出现警告,您会得到预期的结果。修复警告也会修复您的代码(警告摘录,编辑掉多余的警告):

$ gcc -Wall toto.c
toto.c: In function 'main':
toto.c:8:10: warning: passing argument 1 of 'gets' from incompatible pointer type
gets(palavra);
^
In file included from toto.c:1:0:
c:\gnatpro\7.4.2\x86_64-pc-mingw32\include\stdio.h:491:17: note: expected 'char *' but argument is of type 'int *'

^
In file included from toto.c:1:0:
c:\gnatpro\7.4.2\x86_64-pc-mingw32\include\stdio.h:491:17: note: expected 'char *' but argument is of type 'int *'
char *__cdecl gets(char *_Buffer) __MINGW_ATTRIB_DEPRECATED_SEC_WARN;
^
^
toto.c:11:5: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int *'
[-Wformat=]
printf("%s\n",frase);
^
toto.c:14:31: warning: passing argument 1 of 'strlen' from incompatible pointer type
int tamanhoPalavra=strlen(palavra);
^

关于字符比较错误输出并且在C中没有比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com