Search code examples
cscanf

How to extract string-only from stdin using Scanf?


I am a beginner of C and trying to extract Characters from standard input.

  • Input = "C0h1r2i3s4"
  • Expected Outcome = "Chris"

I've tried two ways to achieve this:

  1. Use scanf to store input in one variable -> traverse through input one character a time -> if that character is not a number in ASCII table, store that character in a variable

  2. Use fgets to get input and store in one variable -> traverse through input one character a time -> if that character is not a number in ASCII table, store character in a variable

I wonder if it's possible to use scanf/fgets to get only the characters from stdin? So that I don't have to traverse through every characters.

I've tried to use scanset below, but it seems scanf always screens at character-level and stops when the next char does not fit specified format.

Anyway, I wonder if there is a more powerful use of scanset & scanf.


Code for scanf()

#include <stdio.h>
#include <stdlib.h>
    
void main()
{
char str[50];
//intput = C0h1r2i3s4
scanf("%s", &str); // str = "C0h1r2i3s4"
        
//intput = C0h1r2i3s4
scanf("%*c%*d%s", &str); // str = "h1r2i3s4" -> C & 0 is ignored
        
//intput = C0h1r2i3s4
scanf("%[A-Z,a-z]%*d%s", &str); // str = "C" -> are they a valid format identifier? "%[A-Z,a-z]%*d%s"
} 

Solution

  • Just want to close this question in case someone else is looking for similar one

    In C, there is no simple way to extract certain characters directly from stdin.

    • first, we need to read the complete inputs from stadin
    • then, we travers through the inputs to decides which characters are in concern

    Thank you, the-busybee, for your comment that saved my life earlier this year. I cannot add a comment due to not enough reputation on GitHub, and I just realized that I could reply to my own post.