C与C++的输入输出操作
在printf和scanf中可以使用以"%"开头的控制符,指明要输入或输出的
数据的类型以及格式。
这里提醒一下,vs在使用scanf时候会说scanf不安全而报错,有两种解决方案
1.你就按他说的,乖乖用scanf_s就好了
2.你就在头文件中忽视这个报错
#pragma warning(disable:4996);
或者在项目属性里关闭SDL也行
如果你很想用scanf,sscanf之类的,还是用第二种方法方便
int n = 3;
printf("I want to buy %d books for %f dollars",3,4.5);
double f;
scanf("%d%f",&n,&f);
在printf和scanf中可以使用以"%"开头的控制符,指明要输入或输出的
数据的类型以及格式。
如下表所示
#include <iostream>
#include <cstring>
#include <cstdio>//要用scanf,printf的记得写这个头文件,或者写<stdio.h>
using namespace std;
int main()
{
char c;
int a;
double b;
scanf("%d%lf%c",&a,&b,&c);//可以同时读入不同类型的变量,我这里不是用vs就不像上面那样搞了
printf("%d %lf %c\n",a,b,c);
return 0;
}
input:1 1.2 c
output:1 1.200000 这里看得出来这个c把我打得空格都进去了。变量c就是空格。
想要成功读入c,那么就不再1.2 c之间打这个空格就好了。
如果在输入中有scanf中出现的非控制字符,则这些字符会被跳过
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n,m; char c; float f;
scanf("%d %c,%f:%d",&n,&c,&f,&m);
printf("%d,%c,%f,%d",n,c,f,m);
return 0;
}
input:12 k,3.75:290
output:12,k,3.750000,290
控制printf 输出整数的宽度
%nd(如%4d,%12d) | 以n字符宽度输出整数,宽度不足时用空格填充 |
---|---|
%0nd(如%04d,%012d) | 以n字符宽度输出整数,宽度不足时用0填充 |
%.nf(如%.4f,%.3f) | 输出浮点数,精确到小数点后n位 |
平时还是尽量使用double好,比float精度更高
%x: 以十六进制形式读入或输出整数
%u: 以无符号整数形式输出整数
进制转换
#include <stdlib.h>
#include <stdio.h>
int main()
{
int base, value;
while (scanf("%d", &base)!= EOF)
{
switch (base) {
case 8:
scanf("%o",&value);//输入8进制的数
break;
case 16:
scanf("%x",&value);//输入16进制的数
break;
default://默认输入10进制的数
scanf("%d",&value);
break;
}
printf("%d ", value);
if(value!=0)
printf("0x%x ", value);
else printf("%x ",value);
printf("%04o\n", value);
}
return 0;
}
C++的cout cin
我先在这里说一下,cout cin实际上是对象来的,它的头文件就是iostream
**
详见我的这个博客吧输入输出格式
**
#include <iostream>
using namespace std;
int main()
{
int c;
while((c = cin.get()) != EOF) {
cout << (char)c ;
}
return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char c;
while(scanf("%c",&c) != EOF) {
printf("%c",c);
}
return 0;
}
注意事项:
cin,cout 速度比scanf,printf慢,输入输出数据量大时用后者
一个程序里面不要同时用cin和scanf,不要同时用cout和printf,否则可能会出现很不正常的东西
学会程序和算法,走遍天下都不怕
哈尔滨
如果小伙伴们想我写关于C或C++的什么内容可以在评论区留言给我哦。
主要是因为这部分更新的内容有些参差不齐😂