std :: cin ::和为什么一个换行仍然存在 [英] std::cin:: and why a newline remains

查看:169
本文介绍了std :: cin ::和为什么一个换行仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考资料为什么是控制台

Reference 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 :: sentry std :: cin :: get

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

I chose instead to use std::getline as the while loop is executing twice because the stream is not empty.

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

作为参考,我在上面发布的答案之一, std: :cin 用于读取字符, std :: cin :: get 用于删除换行符 \ n

As the reference I posted above states within one of the answers, std::cin is utilized to read a character and std::cin::get is utilized to remove the newline \n.

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

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

My question is why does std::cin leave a newline \n on the stream?

推荐答案

这是其默认行为,但可以更改。尝试此操作:

Because that's its default behavior, but you can change it. Try this:

#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;
}

将由单个字符和换行符组成的文件\\ n),输出为:

Feeding it a file consisting of a single character and a newline ("a\n"), the output is:

y->a<-
z->
<-

这篇关于std :: cin ::和为什么一个换行仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆