Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple lines of input with scanf()

Tags:

c

scanf

Relevant code snippet:

char input [1024];

printf("Enter text. Press enter on blank line to exit.\n");
scanf("%[^\n]", input);

That will read the whole line up until the user hits [enter], preventing the user from entering a second line (if they wish).

To exit, they hit [enter] and then [enter] again. So I tried all sorts of while loops, for loops, and if statements around the scanf() involving the new line escape sequence but nothing seems to work.

Any ideas?

like image 259
user688604 Avatar asked Nov 27 '12 20:11

user688604


People also ask

Does scanf read line by line?

With scanf("%255[^\n]%*c",line); and the first character read is '\n' , nothing is read into line . line remains as is, possible lacking a null character.

How do I read a new line in scanf?

We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space). We can add a getchar() after scanf() to read an extra newline.

How does %s work in scanf?

In scanf() you usually pass an array to match a %s specifier, then a pointer to the first element of the array is used in it's place. For other specifiers like %d you need to pass the address of the target variable to allow scanf() to store the result in it.


2 Answers

Try this:

while (1 == scanf("%[^\n]%*c", input)) { /* process input */ }
like image 58
tmyklebu Avatar answered Oct 02 '22 16:10

tmyklebu


#include <stdio.h>
int main(){
    char arr[40];
    int i;
    for( i = 0; i < sizeof(arr); i +=2 ){
        scanf("%c%c",&arr[i],&arr[i+1]);
        if( arr[i] == '\n' && arr[i+1] == '\n' )
            break;
    }
    printf("%s", arr);
    return 0;    
}
like image 29
Farhad Hossain Avatar answered Sep 27 '22 19:09

Farhad Hossain