C不是比较字符。我曾多次尝试并且总是遇到问题。
我的代码是
@echo off
title Audit Script
for /F %%i in (C:\testlist.txt) DO call :test %%i
goto :eof <- This jumps to the end of the file
:test
....
....
输入
#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);
}
out
ANA
ANAGOSTADEUMABANANA
进程返回0(0x0)执行时间:4.696 s 按任意键继续。
如此错误,我不知道该怎么做。 请有人帮助我,如果有人能找到问题所在,为什么会这么做。有太多的错误和事情发生,不应该发生。我已经尝试和搜索了这么多次,总是我找到了比较字符串char的方法使用字符串[position] == string2 [position]是正确的但是在这个程序中没有用,我不知道为什么这么多的bug !请有人帮帮我,给我一个灯!我究竟做错了什么?感谢
答案 0 :(得分:2)
你正在定义这样的数组:
int palavra[16];
int frase[201];
虽然它保留了足够的空间,但是当你将char与char进行比较时会出现问题:你可能将int与int(multi-char到multi-char)进行比较,这可能是你想要的(并且你可能有关于指针类型的警告)你忽略了):
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);
^