C - scanf() vs gets() vs fgets()

前端 未结 7 1323
情话喂你
情话喂你 2020-11-22 16:38

I\'ve been doing a fairly easy program of converting a string of Characters (assuming numbers are entered) to an Integer.

After I was done, I noticed some very pecul

7条回答
  •  时光取名叫无心
    2020-11-22 17:16

    You're correct that you should never use gets. If you want to use fgets, you can simply overwrite the newline.

    char *result = fgets(str, sizeof(str), stdin);
    char len = strlen(str);
    if(result != NULL && str[len - 1] == '\n')
    {
      str[len - 1] = '\0';
    }
    else
    {
      // handle error
    }
    

    This does assume there are no embedded NULLs. Another option is POSIX getline:

    char *line = NULL;
    size_t len = 0;
    ssize_t count = getline(&line, &len, stdin);
    if(count >= 1 && line[count - 1] == '\n')
    {
      line[count - 1] = '\0';
    }
    else
    {
      // Handle error
    }
    

    The advantage to getline is it does allocation and reallocation for you, it handles possible embedded NULLs, and it returns the count so you don't have to waste time with strlen. Note that you can't use an array with getline. The pointer must be NULL or free-able.

    I'm not sure what issue you're having with scanf.

提交回复
热议问题