问题描述
我有两个函数,都使用getchar进行输入。
Example1()
用于收集输入并返回值。但是,当连续两次调用此函数时,该函数会将上次调用提交的换行符注册到getchar
。这对我来说没有任何意义,因为我会认为getchar
会被限制在被称为 where 的实际范围内,并在函数本身结束时结束。
int Example1()
{
printf("Gather input from example1\n");
int user_input;
while ((user_input = getchar()) != '\n')
{
return user_input;
}
return 0;
}
Example2()
收集将其存储在新创建的struct成员中的输入。两次调用此函数不会产生与第一个函数相同的问题。
struct foo *Example2()
{
struct foo *user= (struct foo*) malloc(sizeof(struct foo));
printf("Gather input from example2\n");
int user_input
while ((user_input = getchar()) != '\n')
{
user->user_input= user_input;
}
return user;
}
我认为,当函数返回getchar
的实际缓冲区时,该函数调用的范围将消失。是什么原因导致换行符保留在stdin
函数的Example1()
缓冲区中,而不保留在Example2()
函数中?
完整代码:
#include<stdlib.h>
#include<stdio.h>
struct foo {
char user_input;
};
struct foo *Example2()
{
struct foo *user= (struct foo*) malloc(sizeof(struct foo));
printf("Gather input from example2\n");
int user_input;
while ((user_input = getchar()) != '\n')
{
user->user_input= user_input;
}
return user;
}
int Example1()
{
printf("Gather input from example1\n");
int user_input;
while ((user_input = getchar()) != '\n')
{
return user_input;
}
return 0;
}
int main()
{
struct foo *user = Example2();
printf("Example 2 function user_input 1/2 : %d\n",user->user_input);
struct foo *user2 = Example2();
printf("Example 2 function user_input 2/2 : %d\n",user2->user_input);
printf("Example 1 function user_input 1/2 : %d\n",Example1());
printf("Example 1 function user_input 2/2 : %d\n",Example1());
}
解决方法
getchar()
从缓冲区读取一个字符。缓冲区取决于功能范围。
在您的Example1
函数中,return
语句将在getchar()
被调用一次之后执行(无论所读取的字符是否为换行符)。
因此,一次Example1
调用只能读取一个字符,并且它可能只是一行的一部分。如果Example1
仅读取一行的一部分,则后续调用getchar()
(或其他stdin读取函数)将读取该行的左侧部分。
另一方面,在您的Example2
函数中,循环中没有return
语句,并且getchar()
一直执行到读取换行符为止。 (即使已达到EOF!)因此,Example2
将通过一次调用读取直到一行结束。
在第一个函数中,您没有循环,因为您return
位于其主体中,因此最多只能读取一个字符。它减少为if
。
这些函数在任何方面都不等效,并且差异与作用域或使用struct foo
无关。此外,标准输入流(由getchar()
消耗)的状态对于程序是全局的。