2013-04-09 125 views
1

参考Why is the Console Closing after I've included cin.get()?的std :: CIN ::为什么换行仍然

我利用std::cin.get()

#include<iostream>  

char decision = ' '; 
bool wrong = true; 

while (wrong) { 
    std::cout << "\n(I)nteractive or (B)atch Session?: "; 

    if(std::cin) { 
     decision = std::cin.get(); 

     if(std::cin.eof()) 
      throw CustomException("Error occurred while reading input\n"); 
    } else { 
     throw CustomException("Error occurred while reading input\n"); 
    } 

    decision = std::tolower(decision); 
    if (decision != 'i' && decision != 'b') 
     std::cout << "\nPlease enter an 'I' or 'B'\n"; 
    else 
     wrong = false; 
} 

我读basic_istream::sentrystd::cin::get

我选择使用std::getline作为while循环执行两次,因为流不是空的。

std::string line; std::getline(std::cin, line); 

作为参考我张贴上述状态的答案中的一个内,std::cin被用于读取一个字符和std::cin::get来除去换行符\n

char x; std::cin >> x; std::cin.get(); 

我的问题是,为什么std::cin留在流换行符\n

+1

为什么阅读比它更多? – chris 2013-04-09 14:50:54

+0

在C++ I/O是抽象的。没有控制台的概念,所有I/O都通过相同的底层代码。如果您正在读取一个文件,您不希望I/O操作是基于行的,那么您会希望I/O操作读取他们所需的内容,而不再需要它。所以控制台I/O也是如此。 – john 2013-04-09 14:54:37

+1

[为什么cin命令在缓冲区中留下一个'\ n']可能重复(http://stackoverflow.com/questions/28109679/why-does-cin-command-leaves-an-in-the-buffer ) – 2017-03-17 18:59:02

回答

1

因为这是它的默认行为,但是you can change it。试试这个:

#include<iostream> 
using namespace std; 

int main(int argc, char * argv[]) { 
    char y, z; 
    cin >> y; 
    cin >> noskipws >> z; 

    cout << "y->" << y << "<-" << endl; 
    cout << "z->" << z << "<-" << endl; 
} 

喂养它由单个字符和换行符的文件( “A \ n”),输出为:

y->a<- 
z-> 
<- 
0

这很简单。例如,如果您想在阅读时使用存储的城市名称编写文件,则不想使用换行符来读取名称。 除此之外,'\ n'和其他任何字符一样好,通过使用cin,您只需提取一个字符,为什么它应该跳过任何内容? 在大多数情况下,当通过字符读取char时,你不想跳过任何字符,因为可能你想以某种方式解析它,当读取字符串时,你不关心空白等等。