在c++中,我们可以使用cin来输入字符串。但是当它读取数据时读取到空格,就会停止读取。所以,当我们想读取整一行且该行可能出现空格时,cin就不适用了。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    cin>>s;
    cout<<s;
}

输入

Hello world

输出

Hello

在输入中,空格之后的部分没有被读取。那么,我们该如何解决这类问题呢?

我们可以使用getchar()来一个一个字符读取,但这样会有些麻烦。我们可以用getline()这个函数可以读取整行,包括其中的空格。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    getline(cin,s);
    cout<<s;
}

输入

Hello world

输出

Hello world

但是,如果上一行遗留了一个换行,则getline会读取换行而不是读取下一行。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char a,b;
    string s;
    a=getchar();b=getchar();
    getline(cin,s);
    cout<<a<<b<<s;
}

输入

ab
Hello world

输出

ab

所以要用getchar()吃掉接下来的换行

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char a,b;
    string s;
    a=getchar();b=getchar();getchar();
    getline(cin,s);
    cout<<a<<b<<s;
}

输入

ab
Hello world

输出

ab
Hello world
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐