I can’t get around this problem. I need the user to type a string then hit enter, then another string. When he/she is done hit enter once more (this last string would only have \n character so I know when to stop).
char * buff = malloc (100);
printf("Type in strings, to finish hit enter\n");
do{
scanf (" %[^\n]",buff);
//do some other stuff with the string
} while(*buff);
printf("You have finished typing strings\n");
This approach I came up with is no use for me, since the [^\n] command is telling the function to read everything but the \n meaning that the \n is kept in the console buffer. If I simply do
while(*buff)
{
scanf ("%s",buff);
}
if I hit enter it does nothing.
Any other approach?
Yeah,
scanfis actually looking for characters. What you want isgets(to get a line).[edit] as pointed out by Daniel Fischer:
Looks like my advice was not the best. I guess this means use
fgets, as it protects against buffer overrun. Unlikegets, the newline character(s) will also be stored in the string and it is the programmer’s responsibility to check for them.