C/C++ 之输入输出

因为C++向下兼容C,所以有多种输入输出的方式,cin/cout十分简洁,但个人觉得不如scanf/printf来的强大,而且在做算法题时,后者运行速度也快些。

scanf/printf

#include<cstdio>

int main() {
	int n;
	float a,b
	scanf("%d", &n);
	scanf("%f/%f", &p,&q);  //支持类似的输入

	printf("%05d", n);   //不足位补0
	printf("%.5f", a);   //保留小数位
}

sscanf/sprintf

这两个函数并不是用于输入输出,而是类似于string+sacnf/printf,是为了处理字符串问题而生的,将字符串转换为任意类型,或是将任意类型转换为字符串

#include<cstdio>

int main() {
	int n;
	char str1[100] = "123";
	sscanf(str1, "%d", &n); // sscanf的作用是将str1里的内容以%d的格式输入到n中
	int a;
	double b;
	char s1[100]="hello:3.14,2048",s2[100];
	sscanf(s1, "%s:%lf,%d", s2, &b, &a); // 复杂的格式转化

	int m=123;
	char str2[100];
	sprintf(str2, "%d", m); // sprintf的作用是将n中的内容以%d格式输出到str2中
	int x=10;
	double y=20.10;
	char s3[100],s4[100]="hello word";
	sprintf(s3, "%s:%d:%lf", s4, x, y);

	printf("%d %s %lf %d %s %s %s", n,s2,b,a,str2,s2);
}

输出123 hello 3.14 2048 123 hello word:10:20.10

getchar/putchar

这两个函数分别接收和输出一个字符,包括空格和换行符" "
用这个函数循环输入到字符数组中时,不会自动向数组末尾加"",这个字符的意义是结束符,想用printf函数输出时,没有这个结束符就会输出乱码,因此要手动向结尾加"",这也是申明字符数组时总要至少多一个空间的原因。

gets/puts

直接接收字符串,以空格或者换行符作为结束符

原文地址:https://www.cnblogs.com/authetic/p/9460152.html