余生很长,认准一件事,坚持一件事,做成一件事,大胆尝试余下所有的事。
get函数是内置在cin中的一个函数,可以读取任何字符,通过Enter键继续读取下一个字符串(无保存)
以下代码源于此网站 http://c.biancheng.net/view/1346.html
- // This program demonstrates three ways to use cin.get()
- // to pause a program.
- #include <iostream>
- using namespace std;
- int main()
- {
- char ch;
- cout << "This program has paused. Press Enter to continue.";
- cin.get(ch);
- cout << "It has paused a second time. Please press Enter again."; ch = cin.get();
- cout << "It has paused a third time. Please press Enter again.";
- cin.get();
- cout << "Thank you! \n";
- return 0;
- }
在统计一个乱打的字符串中有多少个字母、数字。空格和其他字符时,用cin.get函数
cin 与cin.get之间有啥区别呢?
cin在遇到换行符时会停止,不继续读入下一个从键盘输入的数据;
cin.get遇到换行符时会读取换行符,所以不需要等待用户输入
简单来讲就是cin.get可以直接从键盘接收到数据,不需要用cin>>这样在程序中还得重新指示它让它找到位置准备接受用户的输入
-------------------------------------
那么接下来这道题就很简单了:
统计一个乱打的字符串中的字母数、数字数、空格数以及其他符号数。
可以用一个数组直接记录四种不同类型字符出现的数目,然后用if判断语句,和递加操作来记录次数。
#include<iostream>
using namespace std;
int main(){
int m[4]={0,0,0,0};
char ch;
cin.get(ch);
while(ch!='\n'){
if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z')m[0]++;
else if(ch>='0'&&ch<='9')m[1]++;
else if(ch==' ')m[2]++;
else m[3]++;
cin.get(ch);
}
for (int i=0;i<=3;i++){
cout<<m[i]<<" ";
}
cout<<endl;
return 0;
}