• 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
    }



  • 相关阅读:
    c#基础练习
    一款很厉害的死循环代码
    文字变色逐个出现的特效源码
    IOS开发之UILabel动态高度设置方法
    慎重选择容器类型
    Mac下显示隐藏文件 以及修改 hosts文件内容
    SharePoint 如何使自己的网页自动跳转
    位置和地图:地图的使用
    谈话Java在ThreadLocal理解类
    Android 滑动界面实现---Scroller类别 从源代码和开发文档了解(让你的移动布局)
  • 原文地址:https://www.cnblogs.com/haigege/p/2257304.html
Copyright © 2020-2023  润新知