Reading multiple lines of input with scanf

前端 未结 4 491
时光取名叫无心
时光取名叫无心 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:49

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

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

提交回复
热议问题