Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

programming, C-Language, strings?

I wasn't able to get this in our programming exercise,

"Write a program that accepts a string with maximum string lenghth of 10 characters and displays the number of consonants in the string. (assume that all characters on the string contain letters only.)

i need a sourcecoude on this..pls help T_T i ran out of ideas

1 Answer

Relevance
  • cja
    Lv 7
    1 decade ago
    Favorite Answer

    See below for how I would do this. The assumption you were given, that all characters in the string are letters, is not necessary. As usual, if this is an assignment for a class, I don't recommend handing in my work as if it were your own. I do encourage you to study my code, learn from it, and incorporate my methodology into your own solution.

    Here it is:

    #include <stdio.h>

    #include <string.h>

    #define MAX_LINE 80

    typedef enum { false = 0, true } bool;

    const int maxLen = 10;

    bool isConsonant(char);

    int main(int argc, char *argv[]) {

    char str[MAX_LINE];

    int i,numConsonants = 0;

    bool inputOk = false;

    printf("Enter a string (max length = %d) : ",maxLen);

    do {

    fgets(str,MAX_LINE,stdin);

    if (strlen(str) <= maxLen) {

    *strchr(str,'\n') = '\0';

    inputOk = true;

    } else {

    printf("invalid input, try again\n> ");

    }

    } while (inputOk == false);

    for (i = 0; i < strlen(str); i++) {

    if (isConsonant(str[i]) == true) ++numConsonants;

    }

    printf("\n\"%s\" contains %d consonant%c\n",

    str,numConsonants,(numConsonants != 1) ? 's' : ' ');

    return 0;

    }

    bool isConsonant(char c) {

    static const char consonants[] = "bcdfghjklmnpqrstvwxyz";

    return (strchr(consonants,c) != NULL);

    }

Still have questions? Get your answers by asking now.