0. cin>>ch;
#include<iostream> using namespace std; int main() { char ch; int count=0; cout<<"enter characters:"<<endl; cin>>ch; while(ch!='#') { cout<<ch; ++count; cin>>ch; } cout<<endl<<count<<" characters read\n"; return 0; }
此cin模式忽略空格、换行符,不会回显,也不会加入到字符计数中,遇‘#’号结束;
发送给cin的输入被缓冲。这意味着只有在用户按下回车键后,他输入的内容才会被发送给程序。这就是在运行该程序时,可以在输入‘#’后,继续输入字符的原因。按下回车键后,整个字符序列将被发送给程序,但程序在遇到 # 符后将结束对输入的处理。
1. cin.get(char)
补充cin忽略空格等字符的问题,可以回显空格字符,同时将该类字符加到字符计数中。
#include<iostream> using namespace std; int main() { char ch; int count=0; cout<<"enter characters:"<<endl; cin.get(ch); while(ch!='#') //重复输入字符,遇到‘#’结束; { cout<<ch; ++count; cin.get(ch); } cout<<endl<<count<<" characters read :\n"; return 0; }