我们通常使用cin
和>>
来输入字符或数字,但有时会出现问题,比如cin
遇到空格就会停止,如果我们想输入带空格的字符串,比如"Hello World!"
,它就只能读取到Hello
,如下所示:
#include <iostream>
using namespace std;
int main(){
string str;
cin>>str;
cout<<str<<endl;
return 0;
}
当我们输入Hello world
的时候,输出只有Hello
。
如果我们想要把空格也带上,就需要使用getline()
函数,使用getline()
函数需要用到<string>
标准库,其代码如下所示:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
getline(cin,str);
cout<<str<<endl;
return 0;
}
这样输出结果就会是Hello world
了。