Ok..this problem is kind of confusing because I have to use these 2 functions getc() and ungetc().
What i'm supposed to do is take in input in the form of a string, find all digits, store the digits in the string, convert the string into a digit, and finally print it out. For instance if I have the string "be22again," the number 22 would be taken out to be processed.
The trouble that i'm having is with the ungetc() function. I'm not entirely sure about what it does nor do I really know how to implement it due to the lack of good examples. One website said it:
"The function to unread a character is called ungetc, because it reverses the action of getc"
so far this is what i've come up with (its compilable):
// 1. Read input with getc()
// 2. Check the string for non-digits
// 3. Use ungetc() to unread the non-digits
// 4. Store the digits into a string
// 5. Convert the string into a numerical value with atoi()
// 6. Display the conversion
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define SIZE 100
int main(void)
{
char num_array[SIZE];
int ch, cnt = 0;
puts("Enter a string: ");
while ((ch = getc(stdin)) && isdigit(ch))
{
if (isalpha(ch))
ungetc(ch, stdin);
num_array[cnt] = ch;
cnt++;
}
printf("%d\n", atoi(num_array));
return 0;
}