如何在C ++中将数字读入outfile

时间:2011-04-13 16:36:48

标签: c++ file-io

如何从infile获取数字以用于outfile?

例如,假设我想读取infile中的数字并使用这些数字在outfile上显示为学生ID。

2 个答案:

答案 0 :(得分:0)

这取决于你如何编写值。

显然你需要打开文件 如果您使用outfile << data投放数据,则可能会使用infile >> data阅读。

如果您使用fprintf(),则可能会使用fscanf()阅读,但不一定如此。

首先,您如何向我们展示您编写outfile所做的工作,并快速尝试如何阅读并向我们展示。那么我们可以为您提供一些如何进行的指导。

祝你好运!

<强>更新
你似乎很丢失。我写了一个简短的程序来完成你需要的一些事情,但我没有包含任何评论,所以你需要阅读代码。看看你是否能找到你需要的东西。

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


bool WriteNums(const std::string &sFileName, int nVal, double dVal)
{
    std::ofstream ofstr(sFileName);
    if (!ofstr.is_open())
    {
        std::cerr << "Open output file failed\n";
        return false;
    }
    ofstr << nVal << " " << dVal;
    if (ofstr.fail())
    {
        std::cerr << "Write to file failed\n";
        return false;
    }
    return true;
}

bool ReadNums(const std::string &sFileName, int &nVal, double &dVal)
{
    std::ifstream ifstr(sFileName);
    if (!ifstr.is_open())
    {
        std::cerr << "Open input file failed\n";
        return false;
    }
    ifstr >> nVal >> dVal;
    if (ifstr.fail())
    {
        std::cerr << "Read from file failed\n";
        return false;
    }
    return true;
}

int main()
{
    const std::string sFileName("MyStyff.txt");
    if(WriteNums(sFileName, 42, 1.23456))
    {
        int nVal(0);
        double dVal(0.0);

        if (ReadNums(sFileName, nVal, dVal))
        {
            std::cout << "I read back " << nVal << " and " << dVal << "\n";
        }
    }
    return 0;
}

答案 1 :(得分:0)

istream_iteratorostream_iterator非常有趣。

查看您可以用它做的整洁的事情。这是华氏度到摄氏度转换器的一个简单示例,它读取输入并输出:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>

using namespace std;
typedef float input_type;
static const input_type factor = 5.0f / 9.0f;

struct f_to_c : public unary_function<input_type, input_type>
{
    input_type operator()(const input_type x) const
    { return (x - 32) * factor; }
};

int main(int argc, char* argv[])
{
// F to C
    transform(
        istream_iterator<input_type>(cin),
        istream_iterator<input_type>(),
        ostream_iterator<input_type>(cout, "\n"),
        f_to_c()
    );

    return 0;
}