Search code examples
cstdinfgets

C - Element of fgets in a new variable


I am a beginner in the C language and I'm trying to read the input from a user in the terminal (stdin).I want the user to be able to put as many numbers or characters as he wants until he presses ENTER.

I want to store the second value in a Int variable.

For example the user enters : 45 34 RE 34

I'm trying to use the

fgets(input,1024,stdin)

which gives me an array of characters stored in input, but I need the number after the first space, so 3 and the number after it, 4 in a new variable.

I know it seems pretty easy but I'm having some difficulty doing it, is there an easy code to do that?

Thank you very much!


Solution

  • If you already have the data in the buffer named 'input', it is pretty easy to parse as you describe:

    #include <stdio.h>
    #include <string.h>
    int
    main(void)
    {
            char input[] = "45 34 RE 34";
            int three = 0;
            int four = 0;
            char *space;
    
            space = strchr(input, ' ');
            three = space[1] - '0';
            four = space[2] - '0';
            printf("%d:%d\n", three, four);
            return 0;
    }
    

    Note that you could use scanf to get the values, but scanf is a terrible tool for a beginner, and you would be better off playing with solutions like this to understand what is happening.

    If you don't control the input, you will want to add bounds checking and ensure that strchr finds a value.