Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple lines of input with scanf

Tags:

c

Writing a program for class, restricted to only scanf method. Program receives can receive any number of lines as input. Trouble with receiving input of multiple lines with scanf.

#include <stdio.h>
int main(){
    char s[100];
    while(scanf("%[^\n]",s)==1){
        printf("%s",s);
    }
    return 0;
}

Example input:

Here is a line.
Here is another line.

This is the current output:

Here is a line.

I want my output to be identical to my input. Using scanf.

like image 714
John Avatar asked Dec 04 '22 12:12

John


1 Answers

I think what you want is something like this (if you're really limited only to scanf):

#include <stdio.h>
int main(){
    char s[100];
    while(scanf("%[^\n]%*c",s)==1){
        printf("%s\n",s);
    }
    return 0;
}

The %*c is basically going to suppress the last character of input.

From man scanf

An optional '*' assignment-suppression character: 
scanf() reads input as directed by the conversion specification, 
but discards the input.  No corresponding pointer argument is 
required, and this specification is not included in the count of  
successful assignments returned by scanf().

[ Edit: removed misleading answer as per Chris Dodd's bashing :) ]

like image 127
Michael Avatar answered Dec 24 '22 10:12

Michael