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

我到目前为止,还不知道具体的如何通过C++打开一个文件。下面就是一个问题,求指导。

zclonely 发布于 2013-06-03 09:51, 478 次点击
这我是想把一个关联容器中的每个pair输入到一个.txt文档里,但是就是失败。运行不了。求大神帮忙:
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<map>
using namespace std;
fstream& open_file(fstream& out,const string& file)
{
    out.close();
    out.clear();
    out.open(file.c_str());
    return out;
}
int main()
{
    fstream text1;
    string s("C:Users\Zhchen\Desktop\text1.txt");
    open_file(text1,s);
    map<string,string> mapfile;
    mapfile["'em"]="them";
    mapfile["cuz"]="because";
    mapfile["i"]="I";
    mapfile["nah"]="no";
    mapfile["pos"]="supposed";
    mapfile["sez"]="said";
    mapfile["tanx"]="thanks";
    mapfile["wuz"]="was";
    map<string,string>::iterator map_it=mapfile.begin();
    if(!text1)
        throw runtime_error("no aim file!!");
    while(map_it!=mapfile.end())
        {
            cout<<map_it->first<<"\t"<<map_it->second<<"\n";
            text1<<map_it->first<<"\t"<<map_it->second<<"\n";
            map_it++;
        }
    text1.close();
    int end;
    cin>>end;
    return 0;
3 回复
#2
rjsp2013-06-03 09:56
"C:Users\Zhchen\Desktop\text1.txt";
我猜应该是
"C:\\Users\\Zhchen\\Desktop\\text1.txt";
#3
zclonely2013-06-03 10:12
回复 楼主 zclonely
还是不行啊,它上面显示的Unhandled exception at at 0x754F2005 in 关联容器的使用.exe: Microsoft C++ exception: std::runtime_error at memory location 0x010BF758.
我真的是一头雾水。并且这个文件夹我已经建立好了
#4
zclonely2013-06-03 11:16
回复 2楼 rjsp
谢谢了啊,你说的是对的,字符里面“\\”才能输出“\”。我忘记了 ,这么基础的东西 ,3Q
1