我寫了一個函數,它讀取一個未知長度的字符串,直到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