Which is the best way to get input from user in C?

前端 未结 4 1444
我在风中等你
我在风中等你 2020-11-28 20:59

Many people said that scanf shouldn\'t be used in \"more serious program\", same as with getline.

I started to be lost: if every input fun

4条回答
  •  一生所求
    2020-11-28 21:51

    For simple input where you can set a fixed limit on the input length, I would recommend reading the data from the terminal with fgets().

    This is because fgets() lets you specify the buffer size (as opposed to gets(), which for this very reason should pretty much never be used to read input from humans):

    char line[256];
    
    if(fgets(line, sizeof line, stdin) != NULL)
    {
      /* Now inspect and further parse the string in line. */
    }
    

    Remember that it will retain e.g. the linefeed character(s), which might be surprising.

    UPDATE: As pointed out in a comment, there's a better alternative if you're okay with getting responsibility for tracking the memory: getline(). This is probably the best general-purpose solution for POSIX code, since it doesn't have any static limit on the length of lines to be read.

提交回复
热议问题