I need to write a program square that calculates the squares of all numbers that are contained in a file of floating point numbers. The obtained new numbers form a new file. For example if the file contains the numbers 1, 2.5, 0.1, the numbers 1, 6.25 and 0.01 form the resulting file. The file names are specified on the command line:

square data.txt squares.txt

Thanks in advance! :)

>> Thanks in advance!

Don't thank us. We aren't going to do this for you. Read the rules. You have to show you are willing to put in some effort. Only post here when you get stuck.

This is a very simple program that should give you a little practice with reading and writing simple text files. You need to use ifstream for input file, and ofstream for output file. Then in a loop, read a number, square it, then write it out to the output file. That loop is only three statements long (while, square, write) If it takes you more than three statements then you are probably not coding it correctly. Actually, now that I think about it you could do it in fewer than 3 statements, but that may be pressing it a bit for you right now.

re: Ancient Dragon

2 statements:

Call program, redirecting input from file and output to results file.

1. while read cin into number and not eof(cin)
2. write to cout number^2

done... :-)

Yes, those are the two statements I had in mind. Some new programmers might find the logic easier to follow if they calculate number^2 in a separate statement.

If you want to redirect input from a file you can also use cout and redirect output to a file when the program is run from the command line, script or batch file (depending on the operating system). In that case you don't have to know a thing about ifstream or ofstream.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.