Reading multiple lines of input with scanf

前端 未结 4 474
时光取名叫无心
时光取名叫无心 2020-12-25 08:52

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

相关标签:
4条回答
  • 2020-12-25 09:32

    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;
    }
    
    0 讨论(0)
  • 2020-12-25 09:39

    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;
    }
    
    0 讨论(0)
  • 2020-12-25 09:49

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

    0 讨论(0)
  • 2020-12-25 09:49

    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.

    0 讨论(0)
提交回复
热议问题