Transferring comment to answer.
Your code will work. The code you posted scans everything until a newline character(\n
) is found. But as Jonathan Leffler commented, you never NUL-terminate your string. To do it just use
ch[i]='\0';
after the loop. Also, the user could enter more characters than MAX-1
(One extra for the \0
at the end) and this could cause a buffer overflow. You should add a check like
if(i==MAX-1)
break;
just before your scanf
in order to prevent it from overflowing.
Note that scanf("%s",ch);
will scan until it encounters a space or a newline character.
Instead of looping and scanning character by character, just use
scanf("%[^\n]",ch);
getchar();
The above scanf
scans everything until a newline character is found and puts them in ch
. The getchar()
then discards the \n
from the stdin
. You can also improve safety by limiting the amount of characters that scanf
reads into ch
.
scanf("%49[^\n]",ch);
The above scanf
will scan a maximum of 49 characters and will add a \0
at the end. You can substitute the value of MAX-1
there. I've used 50 as an example.