Search code examples
cstringoutputdigit

How do I extract digits from a C string?


I'm trying to make three simple c programs, but i'll limit this to only one of them since this first question is only specific to one. (Yeah this is hw in case you were curious.)

For this program, the goal is to create one that can take the string:

"BCC  6 T LL 8 9 *** & EXTRA@@@@@"

and output/print

"689"

The code i'll paste below is my sad attempt at this and really I got no results. Any help is appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
{
printf("BCC  6 T LL 8 9 *** & EXTRA@@@@@\n");

char ch=getchar();  
while(ch!='\n')
    {
    if(isdigit(ch)|| ch!='*' || ch!='@')
        printf("%c", ch);
    }
return 0;
}

Solution

  • Try this:

    while ((ch = getchar()) != '\n') {
        if (isdigit(ch) {
            printf("%c", ch);
        }
    }
    

    Your code had one serious problem: you were not calling getchar() inside the while loop. So it would just read one character and repeatedly process that same character. The other problem was your if condition -- the tests for ch != '*' || ch != '@' would be true for all the alphabetic and space characters. If you only want to print digits, there's no need for those tests.

    As I mentioned in the comment, this will process what the user types, not what you print with printf().