如何輸入帶空格的字符串?
0.總結
Get to the key point firstly, the article comes from LawsonAbs!
getline
方法可以輸入帶空格的字符串
1.代碼
#include<iostream>
using namespace std;
void read1(){
string s1,s2;
cin >> s1;//不接受回車,不接受空格,tab
cout << s1<<"\n";
char m=getchar(); //=> 接受換行符
/*
若用換行作爲cin的輸入結束標誌。如果後面還有輸入,那麼就應該將這個回車吸收掉,否則會導致
後面的字符串無法輸入。
*/
getline(cin,s2);//不接受回車,接受空格
if(m=='\n'){
cout <<"m是換行符\n";
}
cout <<s2<<"\n";
}
void read2(){
string s1,s2;
getline(cin,s1);//不接受回車,接受空格
getline(cin,s2);
cout <<"s1="<< s1<<"\n";
cout <<"s2="<<s2<<"\n";
}
int main(){
read1();
read2();
}