C 为什么我的函数没有';不要等待输入?
我编写了一个函数,它读取未知长度的字符串,直到按下Enter键并返回一个字符指针。当我从开关盒内部调用函数时,它不会等待我的输入C 为什么我的函数没有';不要等待输入?,c,input,C,Input,我编写了一个函数,它读取未知长度的字符串,直到按下Enter键并返回一个字符指针。当我从开关盒内部调用函数时,它不会等待我的输入 char *get_paths() { unsigned int length_max = 256; /*Initial length of string*/ unsigned int current_size; current_size = length_max; /* Allocating memory for string i
char *get_paths()
{
unsigned int length_max = 256; /*Initial length of string*/
unsigned int current_size;
current_size = length_max;
/* Allocating memory for string input */
char *tmpStr = malloc(length_max);
/* Simple check to make sure our pointer is not NULL */
if(tmpStr != NULL)
{
int c = EOF;
unsigned int i = 0;
printf("Enter The EXACT or RELATIVE File Paths Separated by a Space: ");
/* Accept input until Enter key is pressed or user inserts EOF */
while((c = getchar()) != '\n' && c != EOF)
{
tmpStr[i] = (char)c;
++i;
/* If memory is filled up, reallocate memory with bigger size */
if(i == current_size)
{
current_size = i + length_max;
/* realloc does magic */
tmpStr = realloc(tmpStr, current_size);
}
}
/* A valid string always end with a '\0' */
tmpStr[i] = '\0';
printf("Got it: %s \n", tmpStr); /*TODO: REMOVE;; USED FOR TESTING*/
return tmpStr;
}
}
开关盒(我在开关块外有一个char*ptr=NULL):
输出:
输入用空格分隔的精确或相对文件路径:明白了:
您很可能在
stdout
上遇到缓冲问题,这是printf
的默认设置。您需要显式刷新stdout
,或者在第一个printf
语句的末尾添加一个换行符,以强制刷新缓冲区。由于在“get it”语句的末尾有一个换行符,因此会发生两个语句(第一个被缓冲)同时打印到输出,因为第二个语句强制刷新缓冲区
另一种可能性是,
stdin
中可能已经有未读数据,当您在while
-循环中调用getchar()
时,它读取先前缓冲的数据,点击换行符,然后退出循环,而不允许您输入新信息。要避免该问题,请执行类似于scanf(“%*[^\n]%*c”)
为了将输入消耗到输入中已经存在的下一个换行符(包括换行符本身),而不必担心缓冲区溢出。我能够找到的解决方案是在第一个printf()
调用之后添加一个getchar()
不知道为什么会这样在第一次printf调用后添加的fflush(stdout)无效。已将\n添加到printf,但不起作用:(您在调用getchar()
之前是否清除了输入?换句话说,可能在stdin
上有其他正在读取的输入?我在另一个函数中使用scanf读取用户输入,为了使用开关,我尝试在getchar()之前添加fflush(stdin)
)调用了
,但它仍然跳过输入。因此,基本上在第一次printf
之后,我有fflush(stdin)
和fflush(stdout)
。永远不要使用fflush(stdin);
对您的代码进行注释很好,但是您的一些注释是非常冗余的,例如“简单检查以确保我们的指针不为空”比if(tmpStr!=NULL)长得多,并且它不会解释代码尚未解释的任何内容。您可能有一个scanf()
的地方留下了一条换行()。您应该在那里清理干净,而不是get\u路径()内
功能。
/*File input*/
case 1:
ptr = get_filepaths();
break;