為什么getline輸入時(shí),我要敲兩次回車才行????
#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
這事因?yàn)間etline函數(shù)決定的,getlime函數(shù)其實(shí)有3個(gè)參數(shù)的,istream& getline ( istream &is , string &str , char delim ); 第三個(gè)是默認(rèn)缺省為'\n',也就是說,換行。getlime將'\n'前面的字符寫入str字符串,也就是name中,當(dāng)然會(huì)去掉'\n',你用的應(yīng)該是VC6.0才會(huì)出現(xiàn)這樣的問題吧,vs已經(jīng)不會(huì)有這問題了。
VC6.0避免按兩次回車的辦法:(網(wǎng)上找到的)
解決方法:進(jìn)入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;?
}
現(xiàn)狀:微軟已經(jīng)確認(rèn)這是他們產(chǎn)品中的'臭蟲'(bug),這個(gè)bug已經(jīng)在Microsoft Visual C++ .NET得到修正.