Home > Back-end >  Scan an int after a letter
Scan an int after a letter

Time:02-08

I'm building a program and I encounter a small problem and I can't find a solution to it. So my goal is to scan a certain letter and when that happens, I just get the number in front of it. Here's the code:

#include <stdio.h>

int main(){

    int pag = 1;
    char *op = malloc(sizeof(char));
    char* opt = malloc(sizeof(char));
            
    printf("P      -> Next\n");
    printf("A      -> Back\n");
    printf("S <N>  -> Jump to N\n");
    printf("B      -> Sair\n");
    printf("\n");

    printf("Insert option: ");
    fgets(op, 4, stdin);
        
    if(op[0] == 'S'){
        
        opt = strsep(&op, " ");
            
        pag = atoi(op);     
    }

    printf("Page: %d\n", pag);

    free(op);
    free(opt);
}

When I execute the program and I chose the option "S 5" for example, my goal is to get the "5". The problem is when I chose a number with more than 2 digits, for example, "S 12" gives me the number "1", not the number 12, I don't know if the problem is with the memory allocation or something else.

CodePudding user response:

First:

char *op = malloc(sizeof(char));
char* opt = malloc(sizeof(char));

won't allocate more than 1 byte for storage of your input string.

fgets(op, 4, stdin);

wont read enough characters for the following string "S 12" as the length parameter value includes the string null terminator.

Try:

const int length= 5;
char *op = malloc(length);
char* opt = malloc(length);

and

fgets(op, length, stdin);
  •  Tags:  
  • Related