zoukankan      html  css  js  c++  java
  • 关于cin,getline一起出现无法正常输入的问题

    int N;
        char c;
        int num=0;
        string s;
         cin>>N>>c;
    
         getline(cin,s,'
    ');
         for(int i=0; s[i]!='';i++)
         {
             num++;
         }
         cout<<num<<endl;

    这时cin(输入流)的状态被标志为遇到文件结尾,如果不调用in.clear()或其他可以清除流的状态的函数来将清除cin的状态,则cin被标志为遇到文件结尾的状态一起保持。到第二个 getline(cin, line)再次引用cin,则此时的cin的状态为遇到文件结束标志,无法输入,因此num始终为0;

    一.调用clear()来清除cin的状态

    二.cin.flush();

    三.cin.ignore();

    总有一款适合你……尝试了好多次,终于可以了!

    string word;
    // read until end-of-file, writing each word to a new line
    cout<<" Now you can input as many words as you can. If you want to terminate, you may press Ctrl+z: ";
    while (cin >> word)
    cout << word << endl;

    cin.clear();//调用clear()来清除cin的状态

    string line;
    // read line at time until end-of-file
    cout<<" Now you can input as many lines of words as you wish. To terminate, please press Ctrl+z: ";
    while (getline(cin, line))
    cout << line << endl;
    cin.clear();

    keep_window_open();

  • 相关阅读:
    类与对象
    类的声明与实例化
    面向对象的基本概念
    css下拉导航栏代码
    面向对象的三大特性
    面向对象三大基本特性,五大基本原则
    dom事件
    PHP 流程
    权限 查找
    留言板案例
  • 原文地址:https://www.cnblogs.com/lyqf/p/8614359.html
Copyright © 2011-2022 走看看