I want to read all the text entered until a new line character is entered.
This is my code.
int i=0;
char ch[MAX];
printf("Enter the text\n");
while(true)
{
scanf("%c",&ch[i]);
if(ch[i]=='\n')
break;
i++;
}
But when I try to execute it reads only one word.
I have also tried scanf("%s",ch);
but the result is the same.
scanf() reads input until it encounters whitespace, newline or End Of File(EOF) whereas gets() reads input until it encounters newline or End Of File(EOF), gets() does not stop reading input when it encounters whitespace instead it takes whitespace as a string.
When you encounter a newline ('\n') or you reach end of input, you stop. Here is the implementation which reads lines of input into an array and then displays the array. int n; while((scanf("%d",&n)) != EOF) { printf("%d",n); //other operations with n.. }
We should use "%[^\n]", which tells scanf() to take input string till user presses enter or return key. Scanf scans till user presses enter or till user presses return key.
An '\n' - or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input.
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.
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.
You're not checking that scanf()
succeeds before relying on ch[i]
to have a valid value, that's not a good idea.
Just use fgets()
to read a whole line at once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With