注册 登录
编程论坛 C++教室

在c++primer有关文件流的问题

shfe 发布于 2013-04-16 16:57, 443 次点击
请帮我看一下下面的程序,我怎么运行不出来
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>

int main()
{
string ifile;
cout<<"Please enter file to sort:";
cin>>ifile;

//构造一个ifstream 输入文件对象
ifstream infile(ifile.c_str());

if(!infile)
{
cerr<<"error:unable to open input file:"<<ifile<<endl;
return -1;
}
string ofile=ifile+".sort";

//构造一个ofstream输出文件对象
ofstream outfile(ofile.c_str());
if(!outfile)
{
cerr<<"error:unable to open output file:"<<ofile<<endl;
return -2;
}

string buffer;
vector<string,allocator>text;

int cnt = 1;
while(infile>>buffer)
{
text.push_back(buffer);
cout<<buffer<<(cnt++%8?" ":"\n");
}
sort(text.begin(),text.end());

//把排序后的词打印到outfile
vector<string,allocator>::iterator iter=text.begin();
for(cnt =  1;iter!=text.end();++iter,++cnt)
outfile<<*iter<<(cnt%8?" ":"\n");
return 0;
}
1 回复
#2
zhuxiaoneng2013-04-16 17:13
修改如下:
程序代码:
#include "stdafx.h"

#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
#include <iostream>

using namespace std;

int main()
{
    string ifile;
    cout<<"Please enter file to sort:";
    cin>>ifile;

    //构造一个ifstream 输入文件对象
    ifstream infile(ifile.c_str());

    if(!infile)
    {
        cerr<<"error:unable to open input file:"<<ifile<<endl;
        return -1;
    }
    string ofile=ifile+".sort";

    //构造一个ofstream输出文件对象
    ofstream outfile(ofile.c_str());
    if(!outfile)
    {
        cerr<<"error:unable to open output file:"<<ofile<<endl;
        return -2;
    }

    string buffer;
    vector<string>text;

    int cnt = 1;
    while(infile>>buffer)
    {
        text.push_back(buffer);
        cout<<buffer<<(cnt++%8?" ":"\n");
    }
    sort(text.begin(),text.end());

    //把排序后的词打印到outfile
    vector<string>::iterator iter=text.begin();
    for(cnt =  1;iter!=text.end();++iter,++cnt)
        outfile<<*iter<<(cnt%8?" ":"\n");
    return 0;
}
1