Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h> /* for memory allocation functions */
- #include <ctype.h> /* for isalnum function */
- #define LINE 80 /* Characters in each line */
- #define MEM_SIZE 100 /* Initial memory size */
- /*gets a char input with an undefined size, counting each char and checking if it's an alpha-numeric char */
- char *getInput(int *counter, int *counteran);
- /*prints the user input in a symmetric way*/
- void printInput(char *input);
- /* This program reads user input with an undefined size, store it in memory according to its size, and prints input in a symmetric way
- then, it prints the total number of char in input, and the number of alpha-numeric chars. */
- int main()
- {
- char *mainInput; /* pointer to the dynamic array, will later be initalized */
- int cnt = 0; /* characters counter */
- int cntan = 0; /* alpha-numeric characters counter */
- printf("Please enter your text:\n");
- mainInput = getInput(&cnt, &cntan); /* sending addresses then storing in them the processed data */
- if (mainInput == NULL)
- {
- return 1;
- }
- printf("\n");
- printf("------------------------------ OUTPUT ------------------------------\n\n");
- printInput(mainInput);
- printf("\n");
- printf("Total Characters: %d\n", cnt);
- printf("Total Alpha-Numeric Characters: %d\n",cntan);
- free(mainInput);
- return 0;
- }
- char *getInput(int *counter, int *counterAN)
- {
- int cntan = 0;
- char *p = (char *)malloc(MEM_SIZE * sizeof(char));
- char *q = p; /*backup pointer, if realloc fails to allocate, function will return last address values stored*/
- int c;
- long current = 0, last = MEM_SIZE - 1;
- while ((c = getchar()) != EOF)
- {
- if (current >= last) /* if reached last bit */
- {
- q = p;
- p = (char *)realloc(q, last + (MEM_SIZE * sizeof(char))); /* attempting to add more bits */
- if (p == NULL)
- {
- printf("Memory allocation failed, printing only stored values \n");
- return q;
- }
- last += MEM_SIZE;
- }
- p[current] = c;
- ++current;
- if (isalnum(c)) /* checking if current char is alpha-numeric */
- cntan++;
- }
- p[current] = '\0';
- (*counter) = current; /* index equals to number of charaters, transfering it through address */
- (*counterAN) = cntan; /* transfering value through address */
- return p;
- }
- void printInput(char *input)
- {
- int line_index = 0, i = 0;
- while (input[i] != '\0') /* until not reached end of input */
- {
- while (line_index < LINE && (input[i] != '\0')) /* printing lines in a symmetric way */
- {
- line_index++;
- putchar(input[i]);
- i++;
- }
- line_index = 0;
- putchar('\n');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement