求助,为什么cinAC了,getline却错了

P1320 压缩技术(续集版)

cuitxf @ 2020-02-17 11:49:02

求助,为什么getline和cin效果不一样,如下 我用的拼接字符串读入,cinAC了,getline就红了几个

```cpp
while (cin>>str1)
{
    len++;
    str += str1;
}

while (getline(cin, str1))
{
    len++;
    str += str1;
}


main函数:

    int main()
    {
        int len = 0, cnt = 0;
        string str, str1;
        while (getline(cin, str1))
        {
            len++;
            str += str1;
        }
        printf("%d ", len);
        if (str[0] == '1')
        {
            printf("0 ");
        }
        char pre = str[0];
        for (int i = 0; str[i]; i++)
        {
            if (str[i] == '0' || str[i] == '1')
            {
                if (str[i] == pre)
                {
                    cnt++;
                }
                else
                {
                    printf("%d ", cnt);
                    cnt = 1;
                }
                pre = str[i];
            }
        }
        printf("%d ", cnt);
        return 0;
    }

by Luisvacson @ 2020-02-17 11:54:26

getline会读整行(包括空格),而cin会读到空格就停


by Luisvacson @ 2020-02-17 11:54:40

@cuitxf


by Alan_Zhao @ 2020-02-17 11:56:18

楼上正解


by SIXIANG32 @ 2020-02-17 12:30:29

@cuitxf 重复使用getline会直接吸收换行符,要加cin.clear();


|