Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanning until new line

Tags:

c

scanf

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.

like image 596
Aditya Kiran Avatar asked Dec 28 '14 13:12

Aditya Kiran


People also ask

Does scanf read until newline?

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.

How do I scan integers until newline?

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.. }

How do I scanf until enter?

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.

What does scanf \n Do?

An '\n' - or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input.


2 Answers

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.

like image 154
Spikatrix Avatar answered Oct 19 '22 23:10

Spikatrix


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.

like image 39
unwind Avatar answered Oct 19 '22 22:10

unwind