C int在应该请求输入时跳过
有人能帮我纠正代码的错误吗?int的行为很有趣,它跳过而不是让我输入一个数字。谢谢大家C int在应该请求输入时跳过,c,C,有人能帮我纠正代码的错误吗?int的行为很有趣,它跳过而不是让我输入一个数字。谢谢大家 #include<stdio.h> #include<stdlib.h> #include<string.h> char* input_text(const char* question) { char* v = (char*)malloc(256); printf("%s ", question); if(fgets(v, 255, stdin) =
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* input_text(const char* question)
{
char* v = (char*)malloc(256);
printf("%s ", question);
if(fgets(v, 255, stdin) == NULL){
free(v);
return(NULL);
}
int len = strlen(v);
if (len > 0 && v[len-1] == '\n'){
v[len-1] = 0;
}
return(v);
}
int input_number(const char* question)
{
int k = 0;
printf("%s", question);
scanf("%d", &k);
return(k);
}
//---------------------------------------------------------------------------------------------------------------------------
int main()
{
char* name = input_text("What is your name? ");
int age = input_number("What is your age? ");
char* bday = input_text("When is your birthday? ");
char* bstfriend = input_text("What is the name of your bestfriend? ");
printf("\n");
printf("Your name is %s \n", name);
printf("Your age is %d \n", age);
printf("Your birthday is %s \n", bday);
printf("Your bestfriend is %s \n", bstfriend);
return(0);
}
另外,重新安排是不允许的,因为它被特别指示这样做 input_number函数在输入年龄后在输入流中留下一个换行符。最简单的修复方法是添加一个getchar,以在scanf in input_number之后使用不需要的换行符:
或者,您可以编写一个函数来清除输入流:
void clear_input(void)
{
int c;
while((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
...
int input_number(const char* question)
{
int k = 0;
printf("%s", question);
scanf("%d", &k);
clear_input();
return(k);
}
scanf和fgets函数并不总是很好地协同工作,因为scanf在输入流中留下了换行符,所以通常最好还是使用fgets。您可以使用sscanf解析输入,然后无需清除输入流,除非用户输入的输入量超过缓冲区所能容纳的量;然后需要处理额外的字符:
int input_number(const char* question)
{
int k = 0;
char buffer[100];
printf("%s", question);
fgets(buffer, sizeof buffer, stdin);
sscanf(buffer, "%d", &k);
return(k);
}
你的代码甚至无法编译。k在哪里声明?@CoolGuy-oops。我的错误。现在编辑它。显示输入。你确定它是被跳过的整数而不是生日的输入吗?与问题无关,但1 char*v=char*malloc256;→ char*v=malloc256;2fgetsv,255,标准输入→ fgetsv,256,stdin 3即使输入文本返回空值,也可以打印所有内容。在这些之后,采取适当的行动4自由姓名、B日期和B朋友printfs@ThingyWotsit我现在编辑了它。我忘了编辑那个部分。对不起,我工作了。非常感谢你!
int input_number(const char* question)
{
int k = 0;
char buffer[100];
printf("%s", question);
fgets(buffer, sizeof buffer, stdin);
sscanf(buffer, "%d", &k);
return(k);
}