输入输出:
- c++输出两位小数:头文件#include<iomanip> cout << fixed << setprecision(2) << a << endl;
- C++:输入任意组数据:while( cin >> t ) (有输入的时候就能继续) C:根据scanf的返回值是接收数据的个数的原理:while(scanf( “%d”, &t )==1) 或者while(scanf (“%d” , &t )!=EOF)
- 字符串输入:
C:注:C语言中字符串要定义为数组str[50]形式
1. scanf(“%s 缺点:遇到空格暂停(%c为单个字符)
2.fgets( str , n , stdin ) 即从输入流中输入n个字符(n输入很大就行了)
3.getchar():只能读取一个字符,用作读取缓冲区的回车等多余字符
C++:注:除string外还是用str[50]形式定义
- string定义:string str; cin >> str; 缺点:遇到空格暂停;
- char str[20]; cin>> str; 缺点:遇到空格停止;
- cin.get(str,n) : 与fgets函数类似,读入n个数,n大点就行
4.cin.getline(str , n , ’ word ’) 当字符串出现words中的特定单个字符时候才停止输入;
5.cin.get() : 与getchar类似,可以清除回车
6.getline ( cin , str ) ; ( str为字符串名称 )
4.输出指定位数小数:#include<iomanip>
double a=3.1415926;
cout << “输出3位小数: ” << fixed << setprecision(3) << a << endl;
cout << “输出3位有效数字” << setprecision(3) << a << endl;
特殊编程语言:
- string 用法:用法很多可以自行搜索;
- strcpy(a,b). b为语言复制的字符串
- 全能头文件 #include<bits/stdc++.h>
特殊方法:
- 四舍五入方法:为对象浮点数+0.5再转化为int类型
- 次方:pow(a,b) 即a的b次方(math.h 头文件)
- 使用制表符 cout << “a\tb\tpow(a,b)” << endl;
- 字符串查找:find()函数:
#include <string>
string s1 = "first second third";
string s2 = "second";
int index = s1.find(s2);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}
- 求长度;
1.数组:sizeof(数组名称)/sizeof(数组类型) 2.字符串长度:strlen(str) (头文件<string.h>) 只能对char str[]使用; size() string a; 只能对string str 使用;
cin >> a;
cout << a.size();
- 将字符串变为大写:将小写的ascll码减去32
- 随机输出a到b的一个整数:#include<stdlib.h>
K= rand() % ( b - a + 1) +a;(循环输出才能体现出随机)
- 获取当前时间:#include<ctime>
int t=time(0);
int h,m,s;
s=t % 60;
m=t / 60 % 60;
h=t / 3600 % 24;
- 数字排序:头文件#include<algorithm> (或者头文件)
Int a[];
sort(a,a+n); (默认为从小到大,起始为a,第n个)
sort ( a,a+n,less<数据类型> ( ) ) 从小到大
sort (a,a+n, greater<数据类型> ( ) ) 从大到小
- 易错点提醒:
1.strcmp(a,b)字符串比较,返回值为0,故作为条件时应当谨慎判断