输入(c/c++算法常用方式)

1.getchar/getche/getch
getchar() —— 从键盘上读入一个字符后继续(回车后继续);
ch=getchar() —— 从键盘上读入一个字符并储存到ch(回车后继续);
getche() —— 从键盘上读入一个字符并立即继续;
getch() —— 从键盘上读入一个字符(不回显)并立即继续;

2.scanf
scanf(" ",& ) —— 按格式输入并赋值变量,部分情况下可巧妙利用
eg:
题目:去掉数字的最高位并输出
输入样例:48576
输出样例:8576


#include<stdio.h>
#include<iostream>
using namespace std;

int main(){
	char ch;
	int n;
	scanf("%c%d",&ch,&n);
	cout << ch << endl;
	return 0;
}

3.gets
gets(s) —— 输入字符串,遇到回车停止输入,当读入的字符串中含有空格时使用(或用scanf(“%s”,s));
eg:当遇到题目要求输入一个空行结束输入时,可以利用gets达到要求,例如输入单词表程序

#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;

int main(){
	int c,count,n=0;
	char w[100][11],t[11],t1[11],t2[11];
	
	//因为gets遇到回车停止输入,当输入空行时,字符串的首位即为'\0'
	while(gets(w[n])){
		if(w[n][0]=='\0') break;
		n++;
	}
	
	while(cin >> t){
		count=0;
		for(int k=0;k<n+1;k++){
			strcpy(t1,w[k]);
			t1[strlen(t)]='\0';
			if(!strcmp(t1,t)) 
				count++;
		}
		cout << count << endl;
	}
	return 0;
}

4.cin
cin >> s —— s可以是任意类型变量或字符串,连续输入时遇到空格或回车停止输入,遇到回车继续程序;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值