C++中cin内容读到string变量要输入两次回车的问题

来源:互联网 发布:电子清标软件 编辑:程序博客网 时间:2024/05/21 19:41

while (getline(cin, line))
 cout << line << endl;
本该在敲回车后,输出line的内容,但是虚多敲一个回车才达到目的。这是vc6.0的一个bug,在vs中此问题不存在。

通过多读一次char的方法放掉这个回车符,这个在C++编程思想里有很详细的解释。

 

[c-sharp] view plain copy
 print?
  1. FIX:   getline   Template   Function   Reads   Extra   Character     
  2.       
  3.   RESOLUTION     
  4.       
  5.   Modify   the   getline   member   function,   which   can   be   found   in   the   following   system   header   file   "string",   as   follows:     
  6.       
  7.     else   if   (_Tr::eq((_E)_C,   _D))     
  8.                 {_Chg   =   true;     
  9.       
  10.           //     _I.rdbuf()->snextc();       //   Remove   this   line   and   add   the   line   below.     
  11.                   _I.rdbuf()->sbumpc();     
  12.                     break;   }     
  13.       
  14.       
  15.   STATUS     
  16.       
  17.   Microsoft   has   confirmed   that   this   is   a   bug   in   the   Microsoft   products   that   are   listed   at   the   beginning   of   this   article.       
  18.       
  19.   This   problem   was   corrected   in   Microsoft   Visual   C++   .NET.     
  20.       
  21.   MORE   INFORMATION     
  22.       
  23.   The   following   sample   program   demonstrates   the   bug:   //test.cpp     
  24.      
  25.   #include   <string>     
  26.   #include   <iostream>     
  27.   int   main   ()   {     
  28.   std::string   s,s2;     
  29.   std::getline(std::cin,s);     
  30.   std::getline(std::cin,s2);     
  31.   std::cout   <<   s   <<'/t'<<   s2   <<   std::endl;     
  32.   return   0;     
  33.   }     
  34.       
  35.   //Actual   Results:     
  36.       
  37.   Hello<Enter   Key>     
  38.   World<Enter   Key>     
  39.   <Enter   Key>     
  40.   Hello       World     
  41.       
  42.   //Expected   Results:     
  43.       
  44.   Hello<Enter   Key>     
  45.   World<Enter   Key>     
  46.   Hello       World     
  47.       
  48.       
  49.   --------------------------------------------------------------------------------     
  50.       
  51.   APPLIES   TO     
  52.   •   The   Standard   C++   Library,   when   used   with:       
  53.       Microsoft   Visual   C++   6.0   Enterprise   Edition       
  54.       Microsoft   Visual   C++   6.0   Professional   Edition       
  55.       Microsoft   Visual   C++   6.0   Standard   Edition  

转自:http://blog.csdn.net/developinglife/article/details/6236260

1 0