0

given a sentence, I would like to be able to count how many vowels are in each word.

Example input:

Hello this is a test for the program.

Example output:

2 1 1 1 1 1 1 2

My first thoughts were to have 2 while loops. The first that will loop until EOF is met to end the program, and the second (nested) while loop will run until a space (" ") is met, while also summing vowels in current word. Once a space is met it will print out the current value of vowels, the second while loop will end and start again (vowel counter reset back to 0).

This is the code I have written for this:

#include <stdio.h>
#include <ctype.h>
main() {
  int vowels = 0;
  char c;
  while ((c = getchar()) != '\n') {
    while((c = getchar()) != " "){
      if(tolower(c) =='a' || tolower(c) =='e' || tolower(c) =='i' || tolower(c) =='o' || tolower(c) =='u') vowels++;
    }
    printf("%d", vowels);
  }
}

However this results in syntax error and I cannot figure out my mistake.

line 6:

while ((c = getchar()) != '\n') {

Am I going about this the correct way or is there a different approach I should be taking with this?

Blued00d
  • 140
  • 2
  • 21
  • 1
    *Please* start reading manuals. It should be `int c;`, that's an incredibly important detail. – Kerrek SB Mar 22 '14 at 20:19
  • 1
    Using two loops is wrong. Ignoring the syntax errors, when are you checking the first character of the line for vowel-ness? You get the 'H' in the outer loop and never check before getting the 'e'. Use one loop and code the different cases for vowels, consonants, and other characters. – mpez0 Mar 22 '14 at 21:18
  • 1
    Your program reads *two* characters in a row (two `getchar()`'s, one in each loop). Make *sure* you don't lose characters on the way. – vonbrand Mar 22 '14 at 23:29

2 Answers2

1

Your error is on the next line. It should be while ((c = getchar()) != ' '), with single quotation marks (apostrophes), since you want a character literal, not a string literal.

Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025
  • I have changed to int main(), changed type of c to an int, and replace my quotes with single quotation marks, however now I get.. `line 3: syntax error near unexpected token ('` and `line 3: int main() {'` However, if I return to my original "main()" then it results in the same old syntax errors that are on line 6. – Blued00d Mar 22 '14 at 20:33
0
#include <stdio.h>
#include <ctype.h>

int main() {
    int c, vowels = 0;

    for(;;){
        c = tolower(getchar());
        if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
            ++vowels;
        } else if(isspace(c)){
            printf("%d ", vowels);
            if(c == '\n')
                break;
            vowels = 0;
        }
    }
    printf("\n");
    return 0;
}
BLUEPIXY
  • 38,201
  • 6
  • 29
  • 68