【问题标题】:what doesn't B take 8 as input? c++什么 B 不接受 8 作为输入? C++
【发布时间】:2020-05-13 02:53:26
【问题描述】:

在下面的代码中,输入是9/ 8,那为什么B不把8作为输入呢?

#include <iostream>
using namespace std;

int main(){
    int A, B;
    cin >> A >> B;
}

【问题讨论】:

  • 问问你自己,9/ 中的/ 发生了什么

标签: c++ input output


【解决方案1】:

输入为 9/ 8 为什么 B 不将 8 作为输入?

因为“/8”不是数字。

【讨论】:

    【解决方案2】:

    operator&gt;&gt; 在遇到不适合正在读取的数据类型的字符时停止读取。

    在这种情况下,您对operator&gt;&gt; 的第一次调用正在读取int A,因此它会读取'9' 字符,然后在遇到非数字'/' 字符时停止读取。 '/' 字符保留在输入流中。

    然后您对operator&gt;&gt; 的第二次调用尝试读取int B,但它读取的是'/' 字符而不是'8' 字符,因此读取失败,因为'/' 不是数字。

    您需要忽略'/' 才能读取'8' 字符,例如:

    #include <iostream>
    using namespace std;
    
    int main(){
        int A, B;
        char ignore;
        cin >> A >> ignore >> B;
    }
    

    或者:

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main(){
        int A, B;
        cin >> A >> ws;
        cin.ignore();
        cin >> B;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 2013-05-12
      • 2019-07-14
      • 1970-01-01
      相关资源
      最近更新 更多