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
    }



  • 相关阅读:
    1-4个人博客
    大二上学期软件工程概论学习进度表(第十六周)
    软件工程概论个人总结
    python+selenium 定位元素的主要方法
    python+selenium 元素定位--iframe
    返回字符串中出现最多的字符
    TestNG中 ITestListener 的使用
    对数组对象按某些属性排序方法
    OSX 10.11 cocoapods安装命令: sudo gem install -n /usr/local/bin cocoapods
    IOS启动页设置适应ios8/9
  • 原文地址:https://www.cnblogs.com/haigege/p/2257304.html
Copyright © 2011-2022 走看看