0

This is a very simple question but wherever I look I get a different answer (is this because it's changed or will change in c++0x?):

In c++ how do I read two numbers from a text file and output them in another text file? Additionally, where do I put the input file? Just in the project directory? And do I need to already have the output file? Or will one be created?

3

3 Answers 3

2

You're probably getting different answers because there are many different ways to do this.

Reading and writing two numbers can be pretty simple:

std::ifstream infile("input_file.txt"); std::ofstream outfile("output_file.txt"); int a, b; infile >> a >> b; outfile << a << "\t" << b; 

You (obviously) need to replace "input_file.txt" with the name of a real text file. You can specify that file with an absolute or relative path, if you want. If you only specify the file name, not a path, that means it'll look for the file in the "current directory" (which may or may not be the same as the directory containing the executable).

When you open a file just for writing as I have above, by default any existing data will be erased, and replaced with what you write. If no file by that name (and again, you can specify the path to the file) exists, a new one will be created. You can also specify append mode, which adds new data to the end of the existing file, or (for an std::fstream) update mode, where you can read existing data and write new data.

Sign up to request clarification or add additional context in comments.

3 Comments

I can't get this to work: all i get is 00 in the output file. How do I specify a path for the input?
Nevermind, I got it to work using a different editor. Just something weird about where xcode expects the input file
You'll write the ints without any separator. You won't be able to distinguish 12, 3 from 1, 23 in the output file.
1

If your program is a filter, i.e. it reads stuff from somewhere, and outputs stuff elsewhere, you will benefit of using standard input and standard output instead of named files. It will allow you to easily use the shell redirections to use files, saving your program to handle all the file operations.

#include <iostream> int main() { int a, b; std::cin >> a >> b; std::cout << a << " " << b; } 

Then use it from the shell.

> cat my_input_file | my_program > my_output_file 

1 Comment

You write the ints without any separator. You won't be able to distinguish 12, 3 from 1, 23 in the output.
0

Put in the same folder as the executable. Or you can use a file path to point at it.

It can be created if it does not exist.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.