werty345353534
werty345353534

Reputation: 9

Vowels not counting correctly

I am trying to write a C program to count the number of vowels, keystrokes, and alpha characters. The keystroke counter is working, but the vowel counter is always off by 1 vowel. The alpha counter is not working.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


int main(int argc, char *argv[])
{
  int keystrokes = 0;           //Number of keystrokes.
  int letters = 0;                  //Number of total letters.
  int vowels = 0;               //Number of vowels.
  int i = 0;
  char sentence[0];                  //Chararacter array specified to users input.

 while((sentence[i] = getchar()) != '\n')

  {
      if(sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' ||sentence[i] =='u'|| sentence[i] == 'A' || sentence[i] == 'E' || sentence[i] == 'I' || sentence[i] == 'O' ||sentence[i] == 'U' )
      {
          ++keystrokes;
          ++letters;
          ++vowels;
      }
      else
      {
          if (isalpha(sentence[i]) == 1) // if character is true
          {
              ++keystrokes;
              ++letters;
          }
          else
          {
              ++keystrokes;
              i++;
          }
      }
  }




  printf("SAMPLE OUTPUT, for EACH sentence above:\n");
  printf("Keystrokes %d \n", keystrokes);
  printf("Alpha Characters %d \n", letters);
  printf("Vowels %d \n", vowels);




  return 0;
}

Upvotes: 0

Views: 76

Answers (3)

loup noir
loup noir

Reputation: 3

I agree with Alan AU about replacing sentence with get_char. I also changed the (isalpha(sentence[i]) == 1) to (isalpha(sentence[i])).
I admit that I'm still new to programming, but your code did not increment the letters properly until I made that change.

Upvotes: 0

kaylum
kaylum

Reputation: 14046

Your problem is that you have undefined behaviour caused by memory corruption.

char sentence[0];

That declares a 0 character array. Just get rid of the array and the i index. That is, change char sentence[0] to be something like char current_char and then replace all instances of sentence[i] with current_char.

Upvotes: 1

mvds
mvds

Reputation: 47104

You have a lot of issues here. By saying char sentence[0] you actually say that there is zero bytes of memory to store the input. Accessing sentence[i] will be "out of bounds" and overwrite other parts of memory, leading to undefined behavior.

To start, change char sentence[0] to char sentence[100]. Then look carefully where you increment your counters, i.e. what the if/else flow looks like in your program. To give an example: Currently, when you have a vowel, the check for isalpha() is not reached, nor is the i++.

Upvotes: 2

Related Questions