输入输出格式控制
cin和 cout
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <iostream> #include <iomanip> // 控制输出格式的头文件在此,别忘! using namespace std; int main(){ cout<<setprecision(5) <<123.456789<<endl; cout<<setw(10) <<setfill('*') <<123.456789<<endl; cout<<fixed <<setprecision(3) <<999.123456<<endl; return 0; }
|
注意点
上述的格式控制方法务必牢记,setprecision()、setw()、setfill()是函数,fixed不是调用函数,不要记错。虽然考试一般不怎么会用到,但一旦题目要求控制格式,格式就不能有任何偏差。
printf 和 scanf
示例:
1 2 3 4 5 6 7 8 9 10
| #include <cstdio> // 相当于stdio.h,但是C++中应该使用cstdio int main(){ double x=123.456789; int y=233; printf("%8.4lf",x); printf("%05d",y); printf("%-5d",y); return 0; }
|
一言蔽之:小数点前指有效数字(一共输出了几个数字),小数点后指小数位数,0指空位补0,负号指靠左对齐
补充知识:
cin、cout和printf、scanf中还有将变量以八进制、十六进制格式输出的选项,但极少用到,由于上述内容多需记忆,不在此详述,感兴趣可查看此篇文章。
指针与数组
将指针当作数组使用:
1 2 3 4 5 6
| int* p; p=new int[10];
int* p2; p2=new int(5);
|
数组名和首元素指针的区别:
首先补充一个关键词 sizeof ,用法例如 sizeof(int)
,返回了 int 所占用的内存空间(当然括号内也可以是某个变量),不过我们不用关心具体的返回值。
绝大多数情况下,数组名和首元素指针是没有区别的,但有以下特殊情况:
1 2 3
| int nums={1,2,3}; sizeof(&nums[0]); sizeof(nums);
|
C风格字符串
C风格字符串即为char数组,但其最后一个元素一定是’\0’!
一般用string代替C风格字符串,因为C风格字符串的雷区很多。
常用函数(可略过):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include <cstring> // cstring是string.h头文件中的C++版本,而string.h是C语言提供的标准库
int main(){ strlen(s); strcmp(s1, s2); strcat(s1, s2); strcpy(s1, s2); strncat(s1, s2, n); strncpy(s1, s2, n); const char *cp1 = "A string example"; const char *cp2 = "A different string"; if(cp1 < cp2) ; int i=strcmp(cp1, cp2); i=strcmp(cp2, cp1); i=strcmp(cp1, cp1);
return 0; }
|
switch 语句
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #include <iostream> using namespace std; int main () { char grade = 'D'; switch(grade){ case 'A' : cout << "很棒!" << endl; break; case 'B' : case 'C' : cout << "做得好" << endl; break; case 'D' : cout << "您通过了" << endl; break; case 'F' : cout << "最好再试一下" << endl; break; default : cout << "无效的成绩" << endl; } return 0; }
|
struct
定义方法:
1 2 3 4 5 6 7 8 9
| struct Books // 定义结构图 { char title[50]; char author[50]; char subject[100]; int book_id; } ;
Books book1;
|
typedef
用法:
const
用法:
1 2 3 4 5
| const int num=10;
int* const p1=# const int* p2=#
|
题目
程序改错,思考num2和num3输出结果的原因,将程序的输出结果改为三个0:
1 2 3 4 5 6 7 8 9 10
| #include <iostream> using namespace std;
int nums1[4];
int main(){ int nums2[4]; int *num3=new(4); cout<<nums1[2]<<nums2[2]<<nums3[2]; }
|
设计一个程序,输入两个整数,输出它们的商,要求保留小数点后两位,并且宽度为6,不足用0补齐
设计一个程序,输入一个整数作为操作命令,输出其相对应的响应,(1:向左,2:向右,其他:错误)
https://www.luogu.com.cn/problem/P1179