C++问题,为什么回车两次才输出结果呢??

2025-03-24 07:46:12
推荐回答(2个)
回答1:

因为getline有三个参数,第三个参数是字符串的结束符,也就是当getline遇到这个结束符时,就不在接受输入了,getline默认情况下以回车('\n')作为结束符,第一次按回车表示字符串结束,第二次按回车才开始输出。
你可以通过多读一次char的方法放掉这个回车符。这个在C++编程思想里有很详细的解释,你可以找来看看的。

FIX: getline Template Function Reads Extra Character

RESOLUTION

Modify the getline member function, which can be found in the following system header file "string", as follows:

else if (_Tr::eq((_E)_C, _D))
{_Chg = true;

// _I.rdbuf()->snextc(); // Remove this line and add the line below.
_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.

This problem was corrected in Microsoft Visual C++ .NET.

MORE INFORMATION

The following sample program demonstrates the 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

--------------------------------------------------------------------------------

APPLIES TO
• The Standard C++ Library, when used with:
Microsoft Visual C++ 6.0 Enterprise Edition
Microsoft Visual C++ 6.0 Professional Edition
Microsoft Visual C++ 6.0 Standard Edition

回答2:

之所以输入3行才开始输出,是因为第二个string类的getline函数,如果是在VC6.0下编译的,则必须敲两次回车,多敲了一个空行,微软已证实这是VC6.0的一个Bug。如果是在DEV C++、Code::Blocks、VC2005下编译该程序,则正常输入两行就可以了。所以说VC6.0对标准C++支持不好,建议学习时与其它编译器配合使用。