RedHat iTOps Tube

Wednesday, May 9, 2012

C++: Create two vectors, populate them, send contents to file as two columns.

Hello,



I am a programming newbie. About a month ago I left a post on LQ asking for help to use scripting to manipulate two columns of data in a text file that I have, and received excellent technical help. One of the suggestions was that I try learning a programming language, and that seemed like an interesting challenge, so I've started learning C++.



Here is what I want to do. I want create a one dimensional array and populate it. Then I want to apply a math function to each element of the array. Lastly, I want to send the contents of the array to a file as column one, and send the results of the math function to the same file as column two.



I am learning from a website called cplusplus, and I am stuck.



First, I learned how to make a counter send its output to the console. Here's that program, basically as presented at the aforementioned website.




Quote:









#include <iostream>

using namespace std;



int n;



int main ()

{

for (int n = 0; n<10; n++)

{

cout << n;

cout << '\n';



}



return 0;

}




In this program I learned how to create an array using specified values and then send one of the values to a file.




Quote:









int mark [] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};

int n, result = 0;



int main ()

{

for ( n = 0; n<10; n++ )

{

result = mark[7];

}



//create, open, write, close file

ofstream myfile;

myfile.open ("results.txt");

myfile << result;

myfile.close();



return 0;

}




And in this program it seems I learned how to create an array, do some math, and send the contents to the console.




Quote:









#include <iostream>

using namespace std;



int mark [] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};



int n;



int main()

{

for ( n = 0; n < 10; n++ )

{

cout << mark[n] << '\t' << mark[n]*10 << '\n';



}



return 0;



}




The above program outputs to the screen what I would like to see in a text file.



I thought I could combine the last program with the penultimate program by adding the appropriate fstream header and then directing the mark[n] line to result instead of cout, and many many variations, but all I ever end up with in the text file is 0, or the last two integers of the two columns I want to see. I think what I want to do is probably very simple, but I'm stuck. Any help is greatly appreciated. I would also welcome feedback on whether my question was easy to understand, and if not, how I can improve my question.



Thanks!

Mark



P.S. Ultimately, I'd like to populate the first array 'on the fly' using a counter or something, and then populate a second array with the results of the math function, then send the contents of each array to a two column format in a text file.