【问题标题】:How to read from an input stream into a file stream?如何从输入流读取到文件流?
【发布时间】:2014-10-24 02:31:57
【问题描述】:

我正在尝试将输入流与文件流绑定,我希望从输入流中输入一些内容,然后自动刷新到文件流
它不起作用...我从键盘输入了一些东西,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;

}

【问题讨论】:

  • 你真正想在这里做什么?重新分配cin 缓冲区?因为这不是tie 管理的。

标签: c++ stream


【解决方案1】:

您的程序太复杂并且误用了 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;
}

它逐个字符地读取,直到找到一个 .

【讨论】:

    【解决方案2】:

    错误:

    • 如果你不捕捉它为什么要抛出异常......

    • 请关闭文件

    • 您是否将文件中的数据放入临时文件并通过它找到“。”和 结束程序?

    • 为什么要用指针来表示 old_tie 用它来做第一个 ofstream 文件 像这样 ofstream * 文件。

    • 修复 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

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

    【讨论】:

    • 提示:使用std::getline 而不是cin.getline 来摆脱那个讨厌的数组。
    • OP 想从输入流中输入一些东西,所以 std::getline 不能工作,因为你需要 cin.getline 来获取输入流。
    猜你喜欢
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2012-02-06
    • 2011-02-12
    • 2013-06-03
    相关资源
    最近更新 更多