关于C++字符串读入的问题

这本来是一道很简单的题~

题目描述

输入什么输出什么,以`结束

输入输出格式

输入格式:

 

\

 

输出格式:

 

\

 

输入输出样例

输入样例#1:
\\\kdjfjdhfhf·
~
sjf`sjfh
输出样例#1:
\\\kdjfjdhfhf·
~
sjf

对,就是这么简单,但我无数次爆零,附上我的0分代码
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    bool b=true;
    string s;
    int l;
    while(cin >> s)
    {
        l=s.size();
        for (int i=0; i < l; i++)
            if (s[i]=='`')
            {
                b=false;
                break;
            }
            else
                cout << s[i];
        cout << endl;
        if (!b)
            break;
    }
    return 0;
}

很正常是不是,所以我想了半天才明白好像cin读入string类型空格和回车使不读入的

所以。。。

下面是正解

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    bool b=true;
    string s;
    int l;
    while(getline(cin,s))
    {
        l=s.size();
        for (int i=0; i < l; i++)
            if (s[i]=='`')
            {
                b=false;
                break;
            }
            else
                cout << s[i];
        cout << endl;
        if (!b)
            break;
    }
    return 0;
}

用getline可以读入整行

虽然问题简单,但还是要注意一下,比赛的时候小心这么丢分

posted @ 2017-04-18 09:30  灵冰斗罗  阅读(290)  评论(0编辑  收藏  举报