Question

So, I am trying to read user input using getline and the error I am having is that, if the user enters "Hi there", when it reads this it thinks there is a line break at the end. So when I try to print it, it prints "Hi there" and then automatically goes to the next line, how can I make it not go to the next line.

Here is my code -

printf(">");
getline(&userinput,&length,stdin);
printf("userinput:%s",userinput);
printf("DONE");

if the user enters - "Is it done?"

It currently prints this -

"Is it done?"
"DONE"

But I want it to print - "Is it done?DONE"

Any help is greatly appreciated

Was it helpful?

Solution

One way is to eliminate the line break from the userinput string:

printf(">");
getline(&userinput,&length,stdin);

char *cp=strchr(userinput, '\n');  /* Find the line-break character (if it exists) */
if(cp)
   *cp = '\0';  /* Convert the line-break character to a string termination character. */

printf("userinput:%s",userinput);
printf("DONE");

OTHER TIPS

getline included the newline character. You can trim that by:

userinput[strlen(userinput)-1] = '\0';

Then, you can print both of them using:

printf("userinput: %s DONE\n", userinput);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top