int main()
{
string line;
// read line at time until end-of-file
while (getline(cin, line))
cout << line << endl;
return 0;
}
C++问题,为什么回车两次才输出结果呢??
答案:2 悬赏:80 手机版
解决时间 2021-03-09 09:38
- 提问者网友:心牵心
- 2021-03-09 04:53
最佳答案
- 五星知识达人网友:十年萤火照君眠
- 2021-03-09 06:27
因为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
你可以通过多读一次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
全部回答
- 1楼网友:煞尾
- 2021-03-09 07:12
cin>>c;
修改为:
cin.read(&c, 1);
函数>>是读串送给c,可以理解为是将输入的串送给c的一个命令;
read是读1(第二个参数)个字节送给c,此时是个命令,同时也是一个字节,如果不输入任意字符直接输入的话,那么read将赋给了c,从而循环。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯