c++入门篇
1.c++中的头文件
比起C语言中的stdio.h
c++的文件换成了iostream
#include <iostream>
using namespace std;
int main(){
//please write your code!
return 0;
}
以及其他的string换成了cstring
#include <iostream>
#include<cstring>
using namespace std;
int main(){
//please write your code!
return 0;
}
还有其他常见的头文件
#include <iostream>
#include <cmath> //数学公式 例如绝对值abs()、幂函数pow()...
#include <string> //C++字符串
#include <string.h> //C语言库,对应C++是cstring
#include <algorithm> //常用函数,max()、min()、abs()、swap()、sort()...
#include <bits/stdc++.h> //万能头文件
using namespace std;
int main(){
//please write your code!
return 0;
}
2.c++的输入与输出
#include <iostream>
using namespace std;
int main(){
int a;
char b;
float c;
cin>>a>>b>>c; //输入a,b,c;
cout<<"1:"<<a<<b<<c<<endl; //输出a,b,c并换行;
string str;
cin>>str; //输入一个字符串
cout<<"2:"<<str<<endl;
getline(cin, str);
cout<<"3:"<<str<<endl;
return 0;
}
3.string常用函数
函数 | 功能 |
---|---|
strcat(char * str1,char * str2) | 把字符串str2接到str1后面,str1最后的’\0’被取消 |
strcpy(char* str1,char* str2) | 把str2指向的字符串拷贝到str1中去 |
strncmp(char *str1,char *str2,int count) | 对str1和str2中的前count个字符按字典顺序比较 |
length()/size() | 计算字符长度 |
c_str() | 输出全部字符 |
compare() | 比较字符串大小 |
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
cin>>s1>>s2;
cout<<s1.compare(s2)<<endl; //s1=s2,return 0; 若s1>s2,return 1; 若s1<s2,return -1
cout<<s1.c_str()<<endl; //输出s1全部字符
cout<<s1.length()<<endl;/ //输出s1的长度
cout<<s1.size()<<endl; //输出s1的长度
}