C: gets() skips the first input [closed]

半城伤御伤魂 提交于 2019-12-02 08:12:08

First, do not use gets, it's unsafe. Use fgets instead.

The reason why the first call to gets skips a line is that there is a '\n' in the buffer at the time that you are making a call to enterRecordDetails(). Typically, the '\n' is a leftover from an earlier input operation, for example, from reading an int with scanf.

One way to fix this problem is to read the string to the end when reading the int, so that the consecutive call of fgets would get the actual data. You can do it in your enterRecordDetails() function:

Record enterRecordDetails()
{
    Record aRecord;
    printf("ENTER THE FOLLOWING RECORD DETAILS:\n");
    printf("   NAME      : ");
    fscanf(stdin, " "); // Skip whitespace, if any
    fgets(aRecord.name, 20, stdin);
    printf("   SURNAME   : ");
    fgets(aRecord.surname, 20, stdin);  
}

Note, however, that fgets keeps '\n' in the string, as long as it fits in the buffer. A better approach would be using scanf, and passing a format specifier that limits the length of input and stops at '\n':

scanf(" %19[^\n]", aRecord.name);
//     ^
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!