string类:getline和cin.geline

本文探讨了在VC++6.0环境中使用getline函数时遇到的双回车问题,并对比了getline与cin.getline的行为差异。通过分析getline函数的工作原理及一个已知的Bug,解释了为何在某些情况下需要按下两次回车才能完成输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
一、问题
两个函数都是存储一个句子。在VC++6.0下,使用getline函数时,当输入一个字符串时,要敲两下回车,这个语句才结束,而用cin.getline则不用。
当运行这个程序时:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string name;
    getline (cin, name);
    cout <<name;
return 0;
}
要想执行cout这个语句时,要敲两次回车才可以,当我输入one sentence[ENTER]时,它并不运行cout这个语句,而是光标还在编绎窗口上闪动,要再按一下[ENTER]才会运行cout这个语句,
而下面这个用cin.getline函数就不用,
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char name[100];
cin.getline (name , 100);
cout <<name;
return 0;
}
 
二、分析如下
1.getline():
Syntax: #include <string> 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. 以下是摘自优快云上的一段文字
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 <string>
#include <iostream>
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<Enter Key>
World<Enter Key>
<Enter Key>
Hello World
//Expected Results:
//预期结果
Hello<Enter Key>
World<Enter Key>
Hello World
三、结论
       的确如文中所说,这是VC6的BUG, 我用标准编译器MinGW和Dev试过了,都是只有一个回车就输出了。也就是说,这是因为VC6对标准C++的不完全支持所导致。
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值