文件输入输出
使用重定向
用freopen可以直接变成由文件输入输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include<stdio.h> #include<iostream> using namespace std;
int main(){ freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); printf("ooo\n"); cout<<"123"<<endl; return 0; }
|
重定向方式写起来简单自然,但是不能同时读写文件和标准输入输出。
使用fopen
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include<stdio.h>
int main(){ FILE *fin,*fout; fin = fopen("in.txt","rb"); fout = fopen("out.txt","wb");
int n; fscanf(fin,"%d",&n); fprintf(fout,"%d",n);
return 0;
}
|
常见的字符串函数的用法
1.tolower(ch)
把字符转换成小写字母,非字母字符不做处理
1 2 3 4 5 6
| char ch[5]={'a','B','C','d'}; char lower_ch[5]; for(int i=0;i<5;i++){ lower_ch[i]=tolower(ch[i]); cout<<lower_ch[i]; }
|
2.strtok(str,",")
以逗号为分隔符,将str切分成一个个子串
1 2 3 4 5
| char ch[16] = "abc,d"; char *p; p = strtok(ch, ","); printf("%s\n", p);
|
3.substr(开始下标,长度)
1 2 3 4 5 6 7 8
| string s1="My name is Ariel."; string s2 = s1.substr(1,3); cout<<"s2="<<s2<<endl;
string s3=s1.substr(4); cout<<"s3="<<s2<<endl;
|
4.insert(开始下标,str)
1 2 3
| string s1="hello"; string s2 = "Ariel!"; s1.insert(2,s2);
|
5.erase(开始下标,长度count)
从开始下标起,删除count个字符。
如果现有长度少于count或count为-1,则删到串尾。
默认情况下,开始下标为0;默认删除到串尾。
6.int find_first_of(char c, int start = 0):
查找字符串中第1个出现的c,由位置start开始。
如果有匹配,则返回匹配位置;否则,返回-1.
默认情况下,start为0。
7.int find_last_of(char c):
找字符串中最后一个出现的c。
有匹配,则返回匹配位置;否则返回-1.