如何正确使用std :: cin.get()和std :: cin.peek()的返回值? [英] How to use correctly the return value from std::cin.get() and std::cin.peek()?

查看:139
本文介绍了如何正确使用std :: cin.get()和std :: cin.peek()的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以这种方式使用 peek(),get():

I've been always using peek(), get() this way:

int main(){

    std::string str;
    int value{};
    if(std::isdigit(std::cin.peek()))
       std::cin >> value;
    else
       std::getline(cin, str);

    std::cout << "value : " << value << '\n';
    std::cout << "str: " << str << '\n';

}

许多C ++网站和论坛都使用这样的东西:

And many C++ websites and forums using such a thing:

while(std::cin.peek() != '\n)
    ; do somthing

  • 但是在阅读了有关C ++入门的注释后,我感到困惑.据说这些函数 get(),peek()返回的是 int 而不是 char ,因此我们不能将结果分配给字符,但变成 int .

    • But after reading the note on C++ primer I am confused. It is said that those functions get(), peek() return an int not a char so we mustn't assign the result into a char but into an int.

      据说那里的字符首先被转换为 unsigned char ,然后被提升为 int .

      It is said there that Characters are converted first to unsigned char then promoted to int.

      那我该如何正确使用这些功能?

      So how could I uses these functions correctly?

      推荐答案

      所以我们不能将结果分配给char而是分配给int

      so we mustn't assign the result into a char but into an int

      while(std :: cin.peek()!='\ n')未将 peek()的结果分配给char.它正在比较一个char和一个int.在这里,char被隐式转换为int,然后进行比较.多亏@MM,以这种方式使用它更安全: while(std :: cin.good()&& std :: cin.peek()!='\ n')

      while(std::cin.peek() != '\n') is not assigning the result of peek() to a char. It is comparing a char and an int. Here the char is implicitly converted to an int and then compared. Thanks to @M.M, it is safer to use it this way: while(std::cin.good() && std::cin.peek() != '\n')

      https://www.learncpp.com/cpp-tutorial/implicit-type-conversion-coercion/

      这篇关于如何正确使用std :: cin.get()和std :: cin.peek()的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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