zoukankan      html  css  js  c++  java
  • C++文件操作

    打开一个文件读入文本,对文本进行操作后存入另一个文件。

    int  main( )
    {
    //读取文件内容
    // string filename;
    // cout<<"please input the filename: "<<flush;
    // cin>>filename;

    ifstream infile;//定义fstream对象并打开文件
    infile.open("testFile.txt");

    if(!infile)
    {
    cerr<<"error: unable to open file "<<endl;
    return -1;
    }

    string str;
    vector<string> vec;
    while(getline(infile, str)) //每次读取一行文件内容存储到vector
    //while(infile>>str) //每次读取一个文件里的单词存储到vector
    {
    vec.push_back(str);
    }

    //将文本输出
    vector<string>::iterator index = vec.begin();
    for( ; index !=vec.end(); ++index)
    cout<<*index<<endl;

    //将每个字母转换为大写字母后存到文件 resultfile.txt
    ofstream outfile("resultfile.txt"); //定义fstream对象并打开文件
    if(!outfile)
    {
    cerr<<"error: unable to open file: resultfile.txt"<<endl;
    return -1;
    }

    //将每个字母都转换为大写字母
    // for(index=vec.begin() ; index !=vec.end(); ++index)
    // {
    // for(string::size_type id=0; id!=index->size(); ++id)
    // (*index)[id] = toupper((*index)[id]);
    // cout<<*index<<endl; //输出到控制台
    // outfile<<*index<<endl; //输出到文件
    // }

    //再将每个单词的首字母转换为大写字母
    string word, line;
    for(index=vec.begin(); index !=vec.end(); ++index) //一行一行的遍历
    {
    istringstream stream(*index); //定义istringstream对象并绑定到 *index
    ostringstream stream2(line); //定义ostringstream对象并绑定到 line
    while(stream>>word) //从对象stream中(已绑定到*index)提取每一行的每一个单词
    {
    word[0] = toupper(word[0]); //首字母转换
    stream2<<word<<""; //将word插入到stream2对象(已绑定到line)(插入空格是为了分离单词)
    }

    *index = stream2.str(); //将stream2对象中的string对象(即line)返回给*index
    cout<<*index<<endl; //输出到控制台
    outfile<<*index<<endl; //输出到文件
    }
    return 1
    }



  • 相关阅读:
    (转)Fiddler 教程
    (转)Web自动化测试之12306火车票网站自动登录工具
    (转)用c#来写个木马程序吧
    (转)windows phone 7 用户控件页面跳转
    (转)自学Windows Phone 7随笔
    (转)Windows Phone7页面导航
    (转)Asp.net生成htm静态文件的两种途径
    (转)HTTP协议详解
    (转)Web自动化测试之12306火车票网站自动登录工具
    收录一些位运算的技巧(不断更新)
  • 原文地址:https://www.cnblogs.com/haigege/p/2257304.html
Copyright © 2011-2022 走看看