I wrote a function that reads an unknown length string until Enter is pressed and returns a char pointer. When I call the function from inside a switch case, it does not wait for my input.
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;
}
}
The switch case (I have a char *ptr = NULL out of the switch block):
/*File input*/
case 1:
ptr = get_filepaths();
break;
Output:
Enter The EXACT or RELATIVE File Paths Separated by a Space: Got it:
The solution I was able to find to ‘somehow’ get away with this issue was to add a
getchar()right after the firstprintf()call. not sure why this works!