标准输入输出函数
字符输入函数:int getchar(void);
字符输出函数:int putchar(int c);
例子:
#include <stdio.h>
int main()
{
char a='a', b='b', c;
c = getchar();
putchar(a);
putchar(b);
putchar('c');
putchar(c);
putchar('\"');
putchar(0101);
putchar('\n');
return 0;
}
运行结果:
s
abcs"A
格式化输入输出
格式化输入函数:scanf
格式化输出函数:printf
例子:
#include <stdio.h>
int main()
{
int num1;
float num2;
char ch1;
int na, nb, nc, nd, ne, nf, ng;
double da, db, dc;
printf("---Basic input and output:---\n");
printf("Input a char, a int and a float:");
scanf("%c %d %f", &ch1,&num1, &num2 );
printf("ch1=%c, num1=%d, num2=%f\n",ch1,num1,num2);
printf( "Please enter seven integers: " );
scanf( "%d%i%i%i%o%u%x", &na, &nb, &nc, &nd, &ne, &nf, &ng );
printf("%d %d %d %d %d %d %d\n", na, nb, nc, nd, ne, nf, ng );
scanf( "%le%lf%lg", &da, &db, &dc );
printf( "%f\n%f\n%f\n", da, db, dc );
return 0;
}
用流进行输入和输出
- cout:标准输出设备,即显示器
- cin:标准输入设备,即键盘
- cerr和clog:标准错误流对象
- 通过cout输出数据 cout<<<表达式1><<<表达式2><...;
- 通过cin输入数据 cin>><表达式1>>><表达式2><...;
例子:
#include <iostream>
using namespace std;
int main()
{
char c ;
int i ;
float x , y ;
cout << "Enter: \n" ;
cin >> i >> x >> y ;
c=i;
cout << "c=" << c << "\ti=" << i;
cout << "\tx="<< x << "\ty=" << y << "\n" ;
return 0;
}
流操纵算子
为流输入输出提供格式化输入输出的功能
常用的流操纵算子:
流操纵算子
|
功能描述
|
setbase(b)
|
以进制基数b为输出整数值
|
setprecision(n)
|
将浮点精度设置为n
|
setw(n)
|
按照w个字符来读或者写
|
flush
|
刷新ostream缓冲区
|
ends
|
插入字符串结束符,然后刷新ostream缓冲区
|
endl
|
插入换行符,然后刷新ostream缓冲区
|
ws
|
跳过空白字符
|
setfill(ch)
|
用ch填充空白字符
|
- 将整数按十进制、八进制和十六进制等形式输出
- 流操纵算子oct——将整数输出形式设置为八进制
- 流操纵算子hex——将整数输出形式设置为十六进制
- 流操纵算子dec——将整数输出形式设置为十进制
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
cout << "Enter a decimal number: ";
cin >> n;
cout << n << " in hexadecimal is: "
<< hex << n << endl
<< dec << n << " in octal is: "
<< oct << n << endl;
return 0;
}
设置浮点数精度
- 流操纵算子setprecision和函数precision都可控制浮点数小数点后面的位数
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
double log2 = log( 2.0 );
int places;
cout << "log(2) with precisions 0-9.\n"
<< "Precision set by the "
<< "precision member function:" << endl;
for ( places = 0; places <= 9; places++ ) {
cout.precision( places );
cout << log2 << '\n';
}
cout << "\nPrecision set by the "
<< "setprecision manipulator:\n";
// 使用setprecision算子
for ( places = 0; places <= 9; places++ )
cout<<setprecision(places)<<log2<<'\n';
return 0;
}
设置域宽
- 函数width可以设置当前域宽(输入输出的字符数)
- 如果输出的数据所需的宽度比设置的域宽小,空位用填充字符(省缺为空格)填充
- 如果输出的数据所需的宽度比设置的域宽大,系统输出所有位
- 流操纵算子setw也可以设置域宽
#include <iostream>
using namespace std;
#define WIDTH 5
int main()
{
int w = 4;
char string[ WIDTH + 1 ];
cout << "Enter a sentence:\n";
cin.width( WIDTH );
while ( cin >> string ) {
cout.width( w++ );
cout << string << endl;
cin.width( WIDTH );
}
return 0;
}