C++的文件处理&string类的知识
一,C++的文件处理
数据类型 | 描述 |
---|---|
ofstream | 输出文件流,用于创建文件并向文件写入信息。 |
ifstream | 输入文件流,用于从文件读取信息。 |
fstream | 表示文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。 |
1.打开文件
在从文件读取信息或者向文件写入信息之前,必须先打开文件。ofstream 和 fstream 对象都可以用来打开文件进行写操作,如果只需要打开文件进行读操作,则使用 ifstream 对象。
下面是 open() 函数的标准语法,open() 函数是 fstream、ifstream 和 ofstream 对象的一个成员。
void open(const char *filename, ios::openmode mode);
模式标志 | 描述 |
---|---|
ios::app | 追加模式。所有写入都追加到文件末尾。 |
ios::ate | 文件打开后定位到文件末尾。 |
ios::in | 打开文件用于读取。 |
ios::out | 打开文件用于写入。 |
ios::trunc | 如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。 |
2.读取方式
(1)逐词读取
void readdatafromfile()
{
ifstream fin("data.txt");
string s;
while (fin >> s)
{
cout << s << " ";//空格是为了避免数据都连在一块儿
}
cout << endl;
}
(2) 逐行读取
void readdatafromfile()
{
ifstream fin("data.txt");
string s;
while (getline(fin, s))
{
cout << "Read from file: " << s << endl; //读取n次(n行)
}
}
(3)输入回车符结束
/* 通过cin.get()检测回车字符,判断输入结束。*/
string value;
while (std::cin >> value)
{
cout<< value<<endl;
if (cin.get() == '\n')
break;
}
二,string和char*的转换,string类的知识
1.char*转string
//string 类型能够自动将 C 风格的字符串转换成 string 对象, 因此 直接赋值即可:
string s1;
const char *pc = "a character array"; //加不加const都行
s1 = pc; // ok
2.string转char*
//c_str()返回了一个指向常量数组的指针, 需常量修饰符 const
//str 被定义为常量指针
const char *str = s1.c_str();
3.string类的知识
//string 类型支持通过下标操作符访问单个字符 例如 在下面的代码段中 字符串中的所有句号被下划线代替
string str( "fa.disney.com" );
int size = str.size();
for ( int ix = 0; ix < size; ++ix )
if ( str[ ix ] == '.' )
str[ ix ] = '_';
//上面代码段的实现可用如下语句替代
replace( str.begin(), str.end(), '.', '_' );