所以我正在尝试编写一个程序,让我使用双向链表数据结构读取用户输入的 MP3 文件数据。我得到了大部分方法和函数的工作,但是当我提示用户输入时,它会在用户输入第一行之前打印出两行。例如
int main()
{
int user_input = 0;
while(!(user_input >= 4))
{
struct MP3_data_node* MP3_data;
MP3_data = (struct MP3_data_node*)malloc(sizeof(struct MP3_data_node));
printf("\nPlease select a number for one of the following instructions:\n");
printf("0: add to list\n1: delete from list\n2: print the list from beginning to end\n3: print the list from end to beginning\n4: exit\n");
scanf("%d", &user_input);
if(user_input == 0)
{
printf("Please provide the artist:");
fgets(MP3_data->artist,50,stdin);
printf("Please provide the album:");
fgets(MP3_data->artist,50,stdin);
printf("Please provide the song title:");
fgets(MP3_data->artist,50,stdin);
printf("Please provide the year the song was released: ");
scanf("%d", &MP3_data->yearReleased);
printf("Please provide the length of the song in seconds: ");
scanf("%d", &MP3_data->runTime);
addToList(MP3_data);
}
...
所以它打印出“请提供艺术家:请提供专辑:”然后让我输入,所以我的问题是如何制作它以便打印: 请提供艺术家:(用户输入) 请提供相册:(用户输入) 等
最佳答案
您在前几个提示中做了正确的事情 (fgets
),然后您切换到 scanf
,这是问题的根源。使用 fgets
(和 strtol
)代替 scanf
,你会没事的。 (而且,第一个 scanf
会导致您的问题中描述的问题。)
问题是 scanf
仅 读取您输入的任何内容的数字部分。这意味着如果您键入 12Enter,则 scanf
会读取 1
和 2
但将 Enter
保留在输入缓冲区中以供下一次调用 fgets
或 scanf
。另一方面,fgets
读取您键入的所有内容,包括 Enter
,从而避免了这个问题。
关于c - fgets 在输入前打印两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18886350/