Readline accepts int from console in C

I want readline to accept int. What is the best way to do this? I have no problem accepting string input as follows:

 char *usrname; // define user input

 /* accept input */
 printf("Enter new name:");
 usrname = readline(NULL);

I understand that having an int will require some error checking before accepting the input.

+3
source share
2 answers

Eduardo Costa answers , but he loses his memory. Better define a function to take care of this for you:

int readint(char *p, char **e)
{
    char *c = readline(p);
    int i = strtol(c, e, 0);
    if(e)
      {
        size_t o = (size_t)(*e - c),
               l = strlen(*e) + 1;
        *e = malloc(l);
        // error checking omitted
        memcpy(*e, c + o, l);
      }
    free(c);
    return i;
}

This version will even save any extra stuff on the line so you can use it later if you need it. Of course, if you need to do a lot with additional materials, you might be better off just reading the line and parsing it yourself, rather than performing such functions.

+6
source

Have you tried something like this?

int i = atoi(readline(NULL));
-4
source

Source: https://habr.com/ru/post/1791728/


All Articles