為什么getline輸入時,我要敲兩次回車才行????
#include<iostream>
#include<string>
using namespace std;
int main()
{
?? ?string name;
?? ?cout<<"Input your name: ";
?? ?getline(cin, name);
?? ?if(name.empty())
?? ?{
?? ??? ?cout<<"input is null...."<<endl;
?? ??? ?return 0;
?? ?}
?? ?if(name == "imooc")
?? ?{
?? ??? ?cout<<"you are a administrator"<<endl;
?? ?}?? ?
?? ?cout<<"hello "<<name<<endl;
?? ?cout<<"name's length: "<<name.size()<<endl;
?? ?cout<<"首字母: "<<name[0]<<endl;
?? ?return 0;
}
2015-09-20
謝謝啊
2015-09-20
這事因為getline函數決定的,getlime函數其實有3個參數的,istream& getline ( istream &is , string &str , char delim ); 第三個是默認缺省為'\n',也就是說,換行。getlime將'\n'前面的字符寫入str字符串,也就是name中,當然會去掉'\n',你用的應該是VC6.0才會出現這樣的問題吧,vs已經不會有這問題了。
VC6.0避免按兩次回車的辦法:(網上找到的)
解決方法:進入X:\Program Files\Microsoft Visual Studio\VC98\Include目錄(VC6.0安裝的地方),用記事本打開string(注意,不是string.h),然后找到以下代碼段.?
else if (_Tr::eq((_E)_C,_D))?
{_Chg = true;?
_I.rdbuf()->snextc(); // 把這一行注釋掉,也可刪掉?
_I.rdbuf()->sbumpc(); //添加這一行,這行本來沒有?
break;?
}
現狀:微軟已經確認這是他們產品中的'臭蟲'(bug),這個bug已經在Microsoft Visual C++ .NET得到修正.