C program to read and store strings

前端 未结 2 1009
囚心锁ツ
囚心锁ツ 2021-01-28 01:47

I\'m writing a piece of code in C that iterates T times and each time takes as input the text of a little song on which it will perform some counting operation (counting the len

相关标签:
2条回答
  • 2021-01-28 02:26

    There's a \n left in the input buffer. One solution is:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX_SONG_SIZE 501
    
    int main(void){
        int t;
        scanf("%d", &t);
        getchar();
    
        char song[MAX_SONG_SIZE];
        while(t--){
            fgets(song, MAX_SONG_SIZE * sizeof(char), stdin);
            printf("foo\n");
        }
        return 0;
    }
    

    See also: How to clear input buffer in C?

    0 讨论(0)
  • 2021-01-28 02:31

    There's a \n left in the input buffer, see http://c-faq.com/stdio/scanfinterlace.html

    A quote from the link:

    As a general rule, you shouldn't try to interlace calls to scanf with calls to gets() (or any other input routines); scanf's peculiar treatment of newlines almost always leads to trouble. Either use scanf to read everything or nothing.

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