我的字符串比较出错了

时间:2014-08-01 18:57:50

标签: c string strcmp

我的程序是输入一个数字,它给出字符串的长度,然后是字符串,最后是一个字母,然后告诉我该字母在字符串中的次数。目前为了帮助我弄清楚我的代码有什么问题我可以看到strcmp导致相同的ascii数字但是为负数。例如,对于字母a,数字是97,但是strcmp给出了-97,因此strcmo不会将字符显示为字符串中的字符并导致错误的结果。任何帮助将不胜感激。谢谢     #包括     #include

int main(void)
{
  char myChar[100], z, k;
  int counter, n, g=0, r, i, l;
  counter=0;
  scanf("%d",&n);
  while (counter<n)
  {
    counter++;
    scanf(" %c",&myChar[counter]);
  }

  scanf(" %s", &z);

  for(i=0;i<n+1;++i)
  {
    k=myChar[i];
    r=strcmp(&z, &k); 
    l=r;    
    //printf("\n%c", myChar[i]);
    printf("%d\n", l);
    if(r==0)
    {
        g++;
        printf("%d\n", g);
    }
  }
  printf("\n\n%d\n", g);


  return (0);
}

1 个答案:

答案 0 :(得分:0)

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

int main(void){
    char myChar[100], str[64];//
    int counter, n;
    int i, j, k;

    printf("number of charactors : ");
    scanf("%d",&n);

    for (i=0; i<n; ++i){
        scanf(" %c", &myChar[i]);
    }

    printf("input string : ");
    scanf("%63s", str);//"%s" : The useless one letter to input as a string. "%c" for &z

    for(i=0;i<n;++i){
        counter = 0;
        for(j=0;str[j]!='\0'; ++j){
            k = (str[j] == myChar[i]);//Comparison of each character
            counter += k;//if(str[j] == myChar[i]) ++counter;
        }
        printf("%c is %d\n", myChar[i], counter);
    }

    return (0);
}