我正在尝试编写一个简单的程序,要求用户从循环中的菜单中进行选择.我使用getchar()来获取输入,但是我注意到当我输入一个字符并按下'Enter'时,程序会产生两个循环(好像我按两次),一个char作为输入,另一个作为'Enter'作为输入.
我该如何解决?
怎么样
#include <stdio.h>
/*! getline() reads one line from standard input and copies it to line array
* (but no more than max chars).
* It does not place the terminating \n in line array.
* Returns line length, or 0 for empty line, or EOF for end-of-file.
*/
int getline(char line[], int max)
{
int nch = 0;
int c;
max = max - 1; /* leave room for '\0' */
while ((c = getchar()) != EOF) {
if (c == '\n')
break;
if (nch < max) {
line[nch] = c;
nch = nch + 1;
}
}
if (c == EOF && nch == 0)
return EOF;
line[nch] = '\0';
return nch;
}
Run Code Online (Sandbox Code Playgroud)