我写了一个函数,它读取一个未知长度的字符串,直到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 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;
}
}
开关壳体(I有一个char * PTR = NULL出开关块):
/*File input*/
case 1:
ptr = get_filepaths();
break;
输出:
输入确切或RELATIVE文件路径分隔的空间:明白了:
哪里是你的交换机的情况下 –
好你的注释你的代码,但是你的一些评论是非常多余的,比如“简单的检查,以确保我们的指针不为NULL”是显著长于'如果(tmpStr! = NULL)',并且它没有解释代码没有解释的任何东西。 – dreamlax