0%

c++:文件读写、字符串

文件输入输出

使用重定向

用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;
//以上两种方式都可以将数据直接写入out.txt文件
//每次运行,out.txt会被重写

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"); //"rb"表示二进制文件只读
fout = fopen("out.txt","wb");

int n;
fscanf(fin,"%d",&n); //指定由fin读入整数n
fprintf(fout,"%d",n); //指定将n输出到fout中

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];
} //输出:abcd

2.strtok(str,",")
以逗号为分隔符,将str切分成一个个子串

1
2
3
4
5
char ch[16] = "abc,d";
char *p;
p = strtok(ch, ",");
printf("%s\n", p);
//输出:abc (换行)d

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;
//输出:s2=Y n
// s3=ame is Ariel.

4.insert(开始下标,str)

1
2
3
string s1="hello";
string s2 = "Ariel!";
s1.insert(2,s2);//输出:heAriel!llo

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.



-------------------本文结束 感谢您的阅读-------------------