开发者

How do i read numbers into an outfile in C++

How do I get numbers from an infile to be used on an outfile?

for example, s开发者_运维问答ay i want to read numbers in an infile and use those numbers to display as student ids on an outfile.


It depends a bit on how you wrote the values.

Obviously you need to open the file.
If you wote the data with outfile << data, you will probably read it with infile >> data.

If you used fprintf(), you will probably read it with fscanf(), though not necessarily.

To start off, how about you show us what you did to write the outfile, and mave a quick try at how you might read it and show us that. Then we can give you some guidence on how to proceed.

Good Luck!

Update
You seem fairly lost. I've written a short program that does some of the things you need, but I haven't included any comments so you need to read the code. Have a look and see if you can figure out what you need.

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


istream_iterator and ostream_iterator are pretty fun.

Check out the neat things you can do with it. Here's a simple example of a Fahrenheit to Celsius converter that reads the input and makes output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜