Search code examples
cinputscanfgets

Reading character and integer separated by spacer in C


I would like to ask if there is a way how to read (stdin) input where is letter(space)number and save the letter to char and number to int. So, basically, I need to say to the "scanf" of "get" that they should stop reading after first spacer is entered. I am looking for easier way than getting string and than reading it character by character.

Thank you so much

Ref. input:

H 1234

Ref. work:

char a='H' int b=1234


Solution

  • You could use scanf like:

    char input[] = "H 1234";
    char c;
    int i;
    
    sscanf(input, "%c %d", &c, &i);
    
    // Prints out the character and the number
    printf("Charcter: %c, integer: %d", c, i);
    
    return 0;