【问题标题】:std::cin:: and why a newline remainsstd::cin:: 以及为什么保留换行符
【发布时间】:2013-04-01 01:28:39
【问题描述】:

参考Why is the Console Closing after I've included cin.get()?

我正在使用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

【问题讨论】:

  • 为什么要多读书?
  • 在 C++ 中,I/O 是抽象的。没有控制台的概念,所有 I/O 都通过相同的底层代码。如果您正在读取文件,您不会期望 I/O 操作是基于行的,您会期望 I/O 操作读取它们需要的内容,而不是更多。所以控制台 I/O 也是如此。

标签: c++ newline cin


【解决方案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->
<-

【讨论】:

    【解决方案2】:

    这很简单。例如,如果您想在读取时写入一个存储城市名称的文件,您将不希望读取带有换行符的名称。 除此之外 '\n' 和其他字符一样好,并且使用 cin 你只是获取一个字符,那么它为什么要跳过任何内容呢? 在大多数用例中,当逐个字符读取时,您不想跳过任何字符,因为您可能想以某种方式解析它,读取字符串时您不关心空格等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多