Wednesday, November 11, 2015

Limbajul C. Contorizarea caracterelor

O problema simpla de C procedural din cursul Cork.

Enuntul:

"2. Write a program to keep count of the occurrence of a user specified character in a stream of characters of known length ( e.g. 50 characters ) input from the keyboard. Compare this to the total number of characters input when ignoring all but alphabetic characters."

Codul:


#include <stdio.h>

int main()
{
    char letter, c = '\0';
    int i = 0, count = 0, dc = 0;
    puts("Enter the letter to count:");
    scanf("%c", &letter);
    _flushall();
    puts("Enter a string of max. 50 characters. If shorter, put 0 at the end. Hit CR.");
    while(i < 50)
    {
       c = getchar();
       if(c != '0')
       {
            if(c == letter) count++;
            if((c >= 65 && c <= 91) || (c >= 97 && c <= 122)) dc++;
       } else break;
       i++;
    }
    printf("\nThe character %c with ASCII code %d has been found %d times.", letter, letter, count);
    printf("\nThere were %d alphabetic characters in the string out of %d characters.", dc, i);
    return 0;
}

Print screen-ul executiei:

No comments:

Post a Comment