0

I have written this code but I have a little problem with it. This code should get a string and check whether this string contains all the alphabet letters... If it doesnt the output is "Not a pangramma!". If it does "PanGramma!". The probem is that I want it to count also the nuumber of the spaces between the words. But when the input is string with at least one space the output will always be "Not a PanGramma!", even if it contains all the alphabet letters. Can someone please help me?

    #include <stdio.h>
    char UpCase (char c);
    int isPangram (char *str);

    int main()
    {
      char str[100];
      printf("Please enter yout string: \n");
      scanf("%s", str);
      if (isPangram (str) == 1)
      {
        printf("PanGramma!\n");
      }
      else
      {
        printf("Not a PanGramma!\n");
      }

        return 0;
    }
    char UpCase (char c)
    {
      if (c>='a' && c<='z')
      {
        return c-'a'+'A';
      }
    return c;
    }
    int isPangram (char *str)
    {
     int i=0;
     int hist[27]={0};
     while (str[i] !=0)
     {
       str[i]=UpCase(str[i]);
       if (str[i] == ' ')
       {
          hist[26]++;
       }
       else
       {
          hist[str[i] - 'A']++;
       }
       i++;
     }
     for (i=0; i<26; i++)
     {
       if(hist[i] == 0)
       {
          return 0;
       }
     }
     return 1;
    }
Michelle
  • 41
  • 4

2 Answers2

0

Your problems comes from the usage of scanf function: it does stops at each white space it catch.

From man scanf:

%s

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

To make your program to work, you can use fgets function:

int main()
{
  char str[100];
  printf("Please enter yout string: \n");
  
  fgets(str, sizeof str, stdin);

  if (isPangram (str) == 1)
  {
    printf("PanGramma!\n");
  }
  else
  {
    printf("Not a PanGramma!\n");
  }

  return 0;
}

If you want to know more on scanf function, you can read A beginners' guide away from scanf(). It will also tell you why scanf could cause a buffer overflow in your code.

Community
  • 1
  • 1
Mathieu
  • 6,922
  • 6
  • 27
  • 37
0

Thank you guys! I have used this scanf ("%[^\n]%*c", str); thanks once again for your help!

Michelle
  • 41
  • 4