• 11
• 27
• 9
• 20
• 31

C++ File I/O With Numbers

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

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 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 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 34 5 67 8 90 1 23 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';     }}