2016-01-08 73 views
1

这里的所有代码我while循环似乎被忽略了我的函数getline

#include <iostream> 
#include <string> 
#include <windows.h> 
#include <stdlib.h> 
using namespace std; 

void Pdelay(string str) 
{ 
    for (char c : str) 
    { 
     std::cout << "" << c << ""; 
     Sleep(100); 
    } 
    std::cout << '\n'; 
} 


int main() 
{ 
    int exit = 1; 
    while (exit == 1) 
    { 

     cout<< "Type something\n:"; 
     string str; 
     str.clear(); 
     getline(cin,str); 
     Pdelay(str); 

     cout << "\n\n[1]Type something again"<< endl; 
     cout << "[2]Exit\n:"; 

     cin >> exit; 
    } 
    return 0; 
} 

每当我运行它,它正常工作第一次全面,当它循环回它跳过函数getline,并用两个COUT继续声明。

+0

这与此有什么关系? – xaxxon

+0

注释:'int exit = 1;'使用不同的名称,因为它可能与['std :: exit']冲突(http://en.cppreference.com/w/cpp/utility/program/exit) ,特别是在使用命名空间标准后(你应该尽量避免)。 – vsoftco

+1

在已经为空的字符串上调用'clear()'没有多大意义。 – molbdnilo

回答

4

紧随使用cin后,换行符会保留在缓冲区中,并被后续的getline“吃掉”。你需要明确的是,额外的换行的缓冲区:

// immediately after cin (need to #include <limits>) 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); 

这就是为什么它不结合std::cinstd::getline一个非常好的主意。前

#include <chrono> 
#include <iostream> 
#include <limits> 
#include <string> 
#include <thread> 

void Pdelay(std::string str) 
{ 
    for (char c : str) 
    { 
     std::cout << "" << c << "" << std::flush; 
     std::this_thread::sleep_for(std::chrono::milliseconds(100)); 
    } 
    std::cout << '\n'; 
} 

int main() 
{ 
    int ext = 1; 
    while (ext == 1) 
    { 
     std::cout << "Type something\n:"; 
     std::string str; 
     str.clear(); 

     std::getline(std::cin, str); 
     Pdelay(str); 

     std::cout << "\n\n[1]Type something again" << std::endl; 
     std::cout << "[2]Exit\n:"; 

     std::cin >> ext; 
     if(!std::cin) // extraction failed 
     { 
      std::cin.clear(); // clear the stream 
      ext = 1; 
     } 
     std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); 
    } 
} 

我才意识到,这个问题已经被问(在一个稍微修改的形式),并且:BTW,你可以写你的代码完全符合标准的C++ 11,没有额外的非库头答案很好:

Why does std::getline() skip input after a formatted extraction?

+0

这在大部分情况下都有效,但现在当我尝试给出输入时,我必须先按Enter键。 *编辑:我没有重新加载页面,没有看到你的编辑。 –

+1

@Smuller除非你使用像[ncurses](https://www.gnu.org/software/ncurses/)这样的专用库,否则你总是必须按ENTER来输入标准C++。 – vsoftco

+0

我的意思是我不得不按输入_before_我开始给予输入,否则它什么都不做或打印空白。 –