ホームページ  >  に質問  >  本文

C++ Cin输入问题

  1. 问题:为什么我在输入完第一组数据后,输入EOF(Ctrl+D)终止第一组数据输入,第二组数据尚未等我输入即已结束?

  2. 相关代码

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main() {
        vector<int> vec1;
        vector<int> vec2;
    
        int tmp;
        cout << "Input the Vec1`s elements:";
        while (cin >> tmp) {
            vec1.push_back(tmp);
        }
    
        cout << endl << "Input the Vec2`s elements:";
    
        while (cin >> tmp) {
            vec2.push_back(tmp);
        }
    
        return 0;
    }
  3. 相关贴图(测试环境:Xcode 7.3.1 OSX EI Capitan)

  4. 个人思考

    • 思考:个人认为,本问题应该属于缓冲区问题,可能是EOF(Ctrl+D)留在了缓冲中,然后直接被读入第二组数据,从而第二组数据未读取即结束。但我尝试在读取第二组数据前增添诸如 fflush(stdin)等清空输入缓冲等方法后,依旧无效。求各位高人指教,谢谢!

高洛峰高洛峰2713日前525

全員に返信(3)返信します

  • 大家讲道理

    大家讲道理2017-04-17 14:24:23

    1.确实是输入问题,但也是流状态位的问题。当输入数字后直接eof会被识别为字符保存在缓冲中,置位的是failbit而不是eof,输入数字后回车换行再eof则是eof置位,下面的程序可以体现这一点。

    2.如果按题主的程序运行,即便正确的进行了eof,由于第一个while结束以后eof置位,所以第二个while循环还是不会执行。当加入clear()后,只要正确eof就可以实现题主预期,进入第二个while循环进行输入。但是如果单纯的只是加入clear方法,而输入时还是直接在数字后面eof时,由于eof被当作字符保存在缓冲中,所以第二个循环开始后,流检测到缓冲中的字符,还是会置位failbit导致循环跳出。

    3.fflush有用。但是要配合cin.clear()使用,因为状态位和缓冲是两个概念,即便清空了缓冲,状态位该是啥还是啥。使用fflush之后可以实现不换行直接eof(cin.clear()后面加上cin.ignore()可实现同样功能)。

    环境:win10 64位+vs2015社区版

    #include <iostream>
    #include <vector>
    #include <stdlib.h>
    
    using namespace std;
    int main() {
        vector<int> vec1;
        vector<int> vec2;
    
        int tmp;
        cout << "Input the Vec1`s elements:";
        while (cin >> tmp) {
            vec1.push_back(tmp);
        }
        cout<<"badbit  is "<<cin.bad()<<endl;
        cout<<"failbit is "<<cin.fail()<<endl;
        cout<<"eofbit  is "<<cin.eof()<<endl;
        cout<<"goodbit is "<<cin.good()<<endl;
    
        cin.clear();
        cin.ignore();
        //fflush(stdin);
    
        cout << endl << "Input the Vec2`s elements:";
    
        while (cin >> tmp) {
            vec2.push_back(tmp);
        }
        //system("pause")
        return 0;
    }

    返事
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:24:23

    详见 c++ reference/istream

    #include <iostream>
    #include <vector>
    
    int main()
    {
      std::vector<int> v1;
      std::vector<int> v2;
      int tmp;
      
      for (; std::cin >> tmp; ) {
        v1.push_back(tmp);
      }
    
      std:: cin.clear();
      
      for (; std::cin >> tmp; ) {
        v2.push_back(tmp);
      }
    
      for (int x : v1) {
        std::cout << x << ' ';
      }
      std::cout << std::endl;
    
      for (int x : v2) {
        std::cout << x << ' ';
      }
      std::cout << std::endl;
      return 0;
    }

    另外,这不是缓冲问题,是 istream 有个表示 eof 的标志位,所以 fflush(stdin) 没用是很正常的。

    返事
    0
  • 黄舟

    黄舟2017-04-17 14:24:23

    研究后,判断问题是环境问题,但是目前还没有找到可以解决这个问题的方法,不知道是不是与编译器有关

    返事
    0
  • キャンセル返事