gpt4 book ai didi

c - gets() 不起作用

转载 作者:行者123 更新时间:2023-12-04 11:20:48 25 4
gpt4 key购买 nike

我有一个用 C 编写的程序,当用户选择选项 3 时,它会从开关调用 gets()。这是我的代码。它似乎没有等待等待用户输入一些东西。而是程序在切换中继续。

void getField();

#include <stdio.h>
#include <string.h>
/*#include "stubs.c"
#include "record.h" */

int debugMode;

void getField(){
char name[25];
char address[80];
int yearofbirth;
char telno[15];
int counter = 0;

if(debugMode == 1){
printf("***DEBUG*** Entering getField function \n");
}

printf("Enter your name:");
gets(name);

printf("Name: %s \n", name);
printf("\n");
}

void main(int argc, char * argv[])
{
struct record* start = NULL;
int userChoice;
debugMode = 0;

if(argv[1] != NULL){
if( (strcmp(argv[1], "debug") == 0) && (argv[2] == NULL) ){
debugMode = 1;
printf("Welcome, to the personal address book application \n");
}
else{
int i = 0;
while(argv[i] != NULL){
printf(argv[i]);
printf(" ");
i++;
}
printf(": Command not found \n");
userChoice = 6;
}
}

if(argv[1] == NULL){
printf("Welcome, to the personal address book application \n");
userChoice = 0;
}


while(userChoice != 6)
{
if(debugMode == 1){
printf("***DEBUG*** Entering do-while loop \n");
}

printf("Enter number corresponding number to option below \n\n");

printf("1) Add a new record in the database \n");
printf("2) Modify a record in the database \n");
printf("3) Print information about a record in the database \n");
printf("4) Print all information in the database \n");
printf("5) Delete an existing record from the database \n");
printf("6) Quit program \n\n >");


scanf("%d", &userChoice);

switch(userChoice){

case 1:
/*addRecord(start, arrayHolder, arrayHolder, 0, arrayHolder);
*/userChoice = 0;
break;
case 2:
/*modifyRecord(start, arrayHolder, arrayHolder, arrayHolder);
*/userChoice = 0;
break;
case 3:
/*printRecord(start, arrayHolder);
*/userChoice = 0;
getField();
break;
case 4:
/*printAllRecords(start);
*/userChoice = 0;
break;
case 5:
/*deleteRecord(start, arrayHolder);
*/userChoice = 0;
break;
case 6:
printf("case 6 \n");
break;
default:
printf("default \n");
userChoice = 0;
break;
}

}
printf("\n");
}

最佳答案

当您使用 scanf() 调用输入选项时,您需要在键盘上键入 2 个键,例如 3 和 ENTER。
scanf() 消耗 '3' 但将 ENTER 保留在输入缓冲区中。
稍后,当您执行 gets() 时,ENTER 仍在输入缓冲区中,这就是 gets() 获取的内容。

你有两个选择:

  • 在每次 scanf()
  • 后清除输入缓冲区
  • 在每次 gets() 之前清除输入缓冲区

要清除输入缓冲区,请使用以下代码:

int clear_input_buffer(void) {
int ch;
while (((ch = getchar()) != EOF) && (ch != '\n')) /* void */;
return ch;
}

哦!并且停止使用gets()gets() 无法安全使用。 使用fgets()相反。

关于c - gets() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1502562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com