C++细节简记

C++细节简记(持续更新)

这里简单记录一些,在编程过程中遇到的C++方面的一些细节问题。

std::cin

在做如下调用class的简单练习时发现:
1.由于所用IDE是Clion,存在一个BUG,第一个while循环在输入结束后,需要用ctrl+d来结束输入,但Clion则会默认程序直接停止运行。
最终在Vim中运行该程序,ctrl-d正常可以结束输入。
2.由于ctrl-d会使得输入缓存中存入结束符,使得下一个cin默认输入的是结束符,会造成错误。此时释放cin,即cin.clear(),清除end-of-file。

#include <iostream>
#include "Stack.h"

int main() {
    Stack st;
    string str;
    while(cin>>str){
        st.push(str);
    }

    if(st.empty()){
        cout<<'\n'<<"Error , no strings"<<endl;
        return 0;
    }
    st.peek(str);
    if(st.size()==1 && str.empty()){
        cout<<'\n'<<"Error , no strings"<<endl;
        return 0;
    }

    cout<<'\n'<<"Read in "<<st.size()<<" strings!"<<endl;

    cout<<"\n There are now "<<st.size()<<"elements in the stack!"<<endl;
    cin.clear();//清除end-of-file的设定,ctrl-d 来跳出输入的while循环,此时cin中存的是结束符,会使得下一次输入直接结束。

    string x;
    cout<<"Would u like to search :";
    cin>>x;
    bool _find=st.find(x);
    int count=_find?st.count(x):0;
    if(_find)
        cout<<"Found "<<x<<" , "<<count<<" times."<<endl;
    else
        cout<<"Not found!"<<endl;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值