开发者

Readline accept int from console in C

I would like to have readline accept an int. What is the best way to accomplish this? I have no problem accepting string input like so:

 char *usrname; // define user input

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

I do understand that having 开发者_StackOverflow社区an int will require some error checking on the before accepting the input.


Eduardo Costa's answer works, but it leaks memory. It's better to 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 preserve 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 the extra stuff you may be better off just reading the line and parsing it yourself rather than with functions like this.


Have you tried something like this?

int i = atoi(readline(NULL));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜