#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
void ex1_xtra2()
{
//输入一个文件名称
string file_name;
cout << "Please enter a file to be opened: (try input.txt or text.txt) ";
cin >> file_name;
//判断是否为空
if ( ! cin || file_name.empty() )
{
cerr << "oops! unable to read file name
"; return;
}
//建立一个读取的ifile,由于读取 input.txt中的内容
ifstream ifile( file_name.c_str() );
if ( ! ifile )
{
cerr << "oops! unable to open input file: "
<< file_name << endl;
return;
}
else
{
cerr << "!! ok: opened " << file_name << " for input
";
}
//新建一个input.txt.sort文件,用于保存排好序的文字
//类型是输出ofile
file_name += ".sort";
ofstream ofile( file_name.c_str() );
if ( ! ofile )
{
cerr << "oops! unable to open output file: "
<< file_name << endl;
return;
}
else
{
cerr << "!! ok: opened " << file_name << " for output
";
}
string word;
vector< string > text;
//读取内容到word至文件末尾
while ( ifile >> word )
{
//插入到容器text中
text.push_back( word );
}
if ( text.empty() )
{
cerr << "bummer! input file is empty: bailing out
";
return;
}
else
{
cerr << "!! ok: read " << text.size() << " strings from input
";
}
//排序操作
sort( text.begin(), text.end() );
int cnt = 0;
for ( vector<string>::iterator iter = text.begin();
iter != text.end(); ++iter )
{
//排列格式
cnt += iter->size() + 1;
if ( cnt > 40 )
{
ofile << '
';
cnt = 0;
}
//输出到ofile中,即input.txt.sort文件中
ofile << *iter << ' ';
}
cout << "ok: wrote sorted strings into " << file_name << endl;
}
int main(void)
{
ex1_xtra2();
return 0;
}
intput.txt
Alice Emma has long flowing red hair.
Her Daddy says when the wind blows
through her hair, it looks almost alive,
like a fiery bird in flight. A beautiful
fiery bird, he tells her, magical but untamed.
``Daddy, shush, there is no such thing,'' she
tells him, at the same time wanting him to
tell her more. Shyly, she asks, ``I mean,
Daddy, is there?''
input.txt.sort
A Alice Daddy Daddy, Emma Her Shyly,
``Daddy, ``I a alive, almost asks, at beautiful
bird bird, blows but fiery fiery flight.
flowing hair, hair. has he her her her, him
him, in is is it like long looks magical
mean, more. no red same says she she shush,
such tell tells tells the the there there?''
thing,'' through time to untamed. wanting when
wind
c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同.
解决的方法有两种:
1.用c_str()函数,下面详细介绍。
2.包含头文件"string"
下面我们进入正题,请出我们的今天的主角 c_str() 他是一个函数哦。。。不要忘记了括号。。