Sign in to follow this  

C++ File I/O With Numbers

This topic is 3872 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need to write a program which reads columns of numbers from a .txt file, performs mathematical operations on them, and outputs the results to a new .txt file. A google search yields many examples of C++ file I/O but all use commands like get() or getline(), which can only work with type char. I've yet to find anything that, for example, will read 8 4 and output 12 to another file. Thanks for your help!

Share this post


Link to post
Share on other sites
well the most basic read from a file is something along these lines:


#include <fstream>

std::ifstream file("c:\\numbers.txt");
int four = 0;
int eight = 0;
file >> four;
file >> eight;
file.close();
int twelve = four + eight;

std::ofstream outfile("c:\\addNumbers.txt");
outfile << twelve << std::endl;
outfile.close();



This is very basic code just to show you reading in a number it will need to be customized for your particular application.

Share this post


Link to post
Share on other sites
Well, if you are reading from a text file you are reading characters...

Fortunately C++ file objects can convert strings to integers just like std::cin and std::cout can. C++ file streams share a lot in common with cin and cout, which I'll assume you are familiar with.

Lets take a simple example of 3 columns, and we just want to sum the 3.

Our input file is:

1 2 3
4 5 6
7 8 9
0 1 2
3 4 5
// etc




We can use code like this:


#include <fstream>
#include <iostream>

int main()
{
// ifstream means input file stream =)
std::ifstream in ("in.txt");
int one, two ,three;
while ( in >> one >> two >> three ) {
int result = one + two + three;
std::cout << result << '\n';
}
}




Output to a file is simple too.
This program will generate a file we could use as input to the above:

int main()
{
std::ofstream out("out.txt");
for( int i = 0 ; i < 300 ; i += 3 )
{
out << i << ' ' << (i+1) ' ' << (i+2) << '\n';
}
}


Share this post


Link to post
Share on other sites

This topic is 3872 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this