首页 > 解决方案 > Even after incrementing the value of the variable it won't change in the while loop

问题描述

    #include <stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<ctype.h>
    int main()
    {
    char s[] = "We promptly judged antique ivory buckles for the next prize";

    for(int i=0;i<strlen(s);i++)
    {
        s[i] = tolower(s[i]);
    }
    int i=0;
    int n=1;
    int counter =0;
    char *s1;
    s1=(char*)malloc(sizeof(char)*n);
    s1[0] = s[0];

    int k=0;
    while(s[i]!='\0')
    {

            for( k=0;k<strlen(s1);++k)
            {
                if(s[i] == s1[k] && s[i] !=' ')
                ++counter;


            }
            if(counter==0 && s[i]!=' ' )
            {
                ++n;

              s1 = realloc(s1, sizeof(char) * (n));
              ++k;
              printf("%d :  %d\n",n,k);
              s1[k] = s[i];
            }


        ++i;
        counter =0;
        k=0;
    }
    s1 =realloc(s1 , sizeof(char)*(n+1));
    s1[n] = '\0';
    printf("%s\n",s1);

    if(n == 26)
    printf("yes");
    else
    printf("No");

    return 0;
}

This program seeks to check whether the word is pangram or not.. It takes a letter from the array s and stores it in array s1 if the letter is not repeated in the latter. Thus if the length of the array s1 after the while loop finishes is 26 it has all the letters possible. But when i tried printing the s1 array it shows only w has its contents.. Confused to the extreme...

标签: c

解决方案


不需要您的++k(在if语句中),将其删除,它将起作用:

    #include <stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<ctype.h>
    int main()
    {
    char s[] = "We promptly judged antique ivory buckles for the next prize";

    for(int i=0;i<strlen(s);i++)
    {
        s[i] = tolower(s[i]);
    }
    int i=0;
    int n=2;
    int counter =0;
    char *s1;
    s1=(char*)malloc(sizeof(char)*n);
    s1[0] = s[0];
    s1[1]='\0';

    int k=0;
    while(s[i]!='\0')
    {

            for( k=0;k<strlen(s1);++k)
            {
                if(s[i] == s1[k] && s[i] !=' ')
                    ++counter;

            }

            if(counter==0 && s[i]!=' ' )
            {
                ++n;

              s1 = realloc(s1, sizeof(char) * (n));
              /* ++k; */  /* <== REMOVE IT */
              printf("%d :  %d\n",n,k);
              s1[k] = s[i];
              s1[k+1]='\0';
            }


        ++i;
        counter =0;
        k=0;
    }
    s1 =realloc(s1 , sizeof(char)*(n+1));
    s1[n] = '\0';
    printf("%s\n",s1);

    if(n == 26)
    printf("yes");
    else
    printf("No");

    return 0;
}

kfor在语句末尾已经增加,因此++k后者是导致错误结果的原因。也s1应该初始化为NULL终止,并且应该在语句NULL内部保持终止,因为它可能包含垃圾。ifs1


推荐阅读