如何在c++中将数字读入输出文件

file io - How do i read numbers into an outfile in C++

本文关键字:输出 文件 数字 c++      更新时间:2023-10-16

如何从文件中获取要在输出文件上使用的数字?

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

这取决于您如何编写这些值。

显然你需要打开文件。
如果您使用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 failedn";
        return false;
    }
    ofstr << nVal << " " << dVal;
    if (ofstr.fail())
    {
        std::cerr << "Write to file failedn";
        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 failedn";
        return false;
    }
    ifstr >> nVal >> dVal;
    if (ifstr.fail())
    {
        std::cerr << "Read from file failedn";
        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;
}

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