如何从输入流读入文件流?

时间:2014-10-24 02:31:57

标签: c++ stream

我正在尝试将输入流与文件流绑定,我希望从输入流中输入内容然后自动刷新到文件流中 它不起作用......我从键盘输入内容,outfile仍然是空的

#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace std;

int main(int argc, char const *argv[])
{
    ofstream outfile("outfile" , ofstream::app | ofstream::out);
    if(!outfile)
        throw runtime_error("Open the file error");
    ostream * old_tie = cin.tie();//get old tie 
    cin.tie(0);//unbind from old tie
    cin.tie(&outfile);//bind new ostream
    string temp;
    while(cin >> temp)
    {
        if(temp == ".")//stop input
            break;
    }
    cin.tie(0);
    cin.tie(old_tie);// recovery old tie
    return 0;

}

2 个答案:

答案 0 :(得分:0)

您的程序太复杂,并且滥用tie()。请尝试以下方法:

#include <iostream>
#include <fstream>
int main() {
    using namespace std;
    ofstream outfile("outfile" , ofstream::app | ofstream::out);
    if(!outfile) {
        cerr << "Open the file error";
        return 1;
    }
    char data(0);
    while(data != '.') {
        cin.get(data);
        cin.clear(); // Prevents EOF errors;
        outfile << data;
    }
    return 0;
}

它通过char读取char,直到找到。

答案 1 :(得分:-1)

错误:

  • 如果你不抓住它,为什么要抛出异常......

  • 请关闭文件

  • 您是否将数据从文件放入temp并通过它来查找&#34;。&#34;和 结束计划?

  • 为什么使用old_tie的指针将它用于第一个ofstream文件 喜欢这个ofstream * file。

  • 修复if语句并中断

  • 包含字符串库 - //这可能会解决您的问题

  • 什么是文件名??

  • 是取消绑定的tie(0)函数吗?

<强> //修改

说明:

一旦找到find_first_of函数的第一个句点,就会创建一个substr并将其复制到outfile中。解决方案是如此高效,每次都有效。逻辑尽可能简单。不要使用不必要的函数并初始化不必要的变量,因为当变量太多时,它更复杂,更容易出错。

解决方案: - 不需要cin.tie()

#include <iostream>
#include <fstream>
#include <string>


using namespace std;

int main(int argc, char const *argv[])
{
    ofstream outfile("outfile" , ofstream::app | ofstream::out);
    string s;
    getline(cin, s);
    int i = s.find_first_of(".");
    if(i!=std::string::npos)
    {
        s = s.substr(0, i);
        outfile << s;
    }
    else
    {
        cout << "No periods found" << endl;
    }

}

已编译的代码 - http://ideone.com/ooj1ej

如果需要解释,请在下面的评论中提问。