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;
}