John
John

Reputation: 139

Reading multiple lines of input with scanf

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.

Upvotes: 4

Views: 52361

Answers (4)

Sudhanshu Agrahari
Sudhanshu Agrahari

Reputation: 1

Try this piece of code.. It works as desired on a GCC compiler with C99 standards..

#include<stdio.h>
int main()
{
int s[100];
printf("Enter multiple line strings\n");
scanf("%[^\r]s",s);
printf("Enterd String is\n");
printf("%s\n",s);
return 0;
}

Upvotes: 0

Puneet Purohit
Puneet Purohit

Reputation: 1281

try this code and use tab key as delimeter

#include <stdio.h>
int main(){
    char s[100];
    scanf("%[^\t]",s);
    printf("%s",s);

    return 0;
}

Upvotes: 6

Michael
Michael

Reputation: 3141

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 :) ]

Upvotes: 10

Thrill Science
Thrill Science

Reputation: 408

I'll give you a hint.

You need to repeat the scanf operation until an "EOF" condition is reached.

The way that's usually done is with the

while (!feof(stdin)) {
}

construct.

Upvotes: 1

Related Questions