我写了一个函数,它读取一个未知长度的字符串,直到按下 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;
}
}
开关盒(我在开关块中有一个 char *ptr = NULL):
/*File input*/
case 1:
ptr = get_filepaths();
break;
输出:
输入以空格分隔的确切或相对文件路径:明白了: