string类:getline和cin.geline

 
一、问题
两个函数都是存储一个句子。在 VC++6.0 下,使用 getline 函数时,当输入一个字符串时,要敲两下回车,这个语句才结束,而用 cin.getline 则不用。
当运行这个程序时:
#include
#include
using namespace std;
int main ()
{
    string name;
    getline (cin, name);
    cout <
return 0;
}
要想执行 cout 这个语句时,要敲两次回车才可以,当我输入 one sentence[ENTER] 时,它并不运行 cout 这个语句,而是光标还在编绎窗口上闪动,要再按一下 [ENTER] 才会运行 cout 这个语句,
而下面这个用 cin.getline 函数就不用,
#include
#include
using namespace std;
int main ()
{
char name[100];
cin.getline (name , 100);
cout <
return 0;
}
 
二、分析如下
1.getline():
Syntax: #include  istream& getline( istream& is, string& s, char delimiter = '/n' );
The C++ string class defines the global function getline() to read strings from and I/O stream. The getline() function, which is not part of the string class, reads a line from is and stores it into s. If a character delimiter is specified, then getline() will use delimiter to decide when to stop reading data.
For example, the following code reads a line of text from STDIN and displays it to STDOUT: string s; getline( cin, s );cout << "You entered " << s << endl;
getline ()是一个流类库的一个成员函数,其书写形式是:cin.geline(v,n);// getline()和cin.geline()应该是一样 ,只是参数不同,其中参数v用来指定存放字符串的缓冲区地址,第二个参数n指定缓冲区长度。使用getline(cin,i,?)函数可以输入带空格的整行字符 ,第三个参数默认为'/n'。
2 . 以下是摘自CSDN上的一段文字
FIX: getline Template Function Reads Extra Character
修正: getline 模板函数读取额外字符
RESOLUTION    解决方案
Modify the getline member function, which can be found in the following system header file "string", as follows:
在系统头文件string中,修改getline成员函数的内容为以下形式(用记事本查找以下代码段定位):
else if (_Tr::eq((_E)_C, _D))
{_Chg = true;
// _I.rdbuf()->snextc(); // 删除这一行,加上以下一行
_I.rdbuf()->sbumpc();
break; }
STATUS   状态
Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.
微软已经证实这是列在本文开始处微软产品中发现的Bug .
This problem was corrected in Microsoft Visual C++ .NET.
该问题已在 Microsoft Visual C++.NET 中修正.
MORE INFORMATION
更多信息
The following sample program demonstrates the bug:
以下程序演示该 Bug:
//test.cpp
#include
#include
int main () {
std::string s,s2;
std::getline(std::cin,s);
std::getline(std::cin,s2);
std::cout << s <<'/t'<< s2 << std::endl;
return 0;
}
//Actual Results:
// 实际结果
Hello
World
Hello World
//Expected Results:
// 预期结果
Hello
World
Hello World
三、结论
       的确如文中所说,这是VC6的BUG, 我用标准编译器MinGW和Dev试过了,都是只有一个回车就输出了。也就是说,这是因为VC6对标准C++的不完全支持所导致。
 

你可能感兴趣的:(string,microsoft,iostream,character,function,c++)