Domanda

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;
}
È stato utile?

Soluzione

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().

Altri suggerimenti

Simply do

while(ch!='\n')
    if(ch >= '0' && ch <= '9')
        printf("%c",ch);

A neat and simple code. No need to call a separate function isdigit(), when you use ch >= '0' it compares the ASCII value of the character and '0' Once the condition hold true, your digit will be printed. Also there is no need to check for '*' and '@' , there can be more such special characters in a new string. How long can you put checks?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top