I've to make several experiments of some algorithms. I want to send those results to a .txt file

``````//....
for (count= 1; count<= 20; count++){
//....
std::cout<<exp<<"Time:  "<<duration << " seconds" <<'\n';

ofstream f2;
f2.open("results.txt", ofstream::out);
for(int i=0; i<=20; i++){
f2<<duration<<endl;
}
f2.close();
}``````

With this code, I only get the same result repeated several times, instead of saving a result per line. What do I need to modify of this code??

What is the purpose of the inner for-loop? That's where you write the same result multiple times.

What do you mean with a result? Your duration variable doesn't change at all during the program. At this moment you are writing 20x20 times duration to results.txt.

What is the purpose of the inner for-loop? That's where you write the same result multiple times.

What do you mean with a result? Your duration variable doesn't change at all during the program. At this moment you are writing 20x20 times duration to results.txt.

I've to do 20 tests of each sorting algorithm, with different ammount of data (from 100 to a million integers)

The first loop is for re-running the program 20 times, so I can get 20 different results. It works fine until there.

For my convenience, I want to send those 20 results to a .txt so I can paste them into tables.

The problem is in the ofstream, it sends the same outcome to the .txt file..

You have to push the results out to the file after every test. By doing the print to file loop after the test loop, you can only print the last result. They need to be within the same loop.

``````//....
ofstream f2;
f2.open("results.txt", ofstream::out); //Open file

for (count= 1; count<= 20; count++){
//.... Run test
std::cout<<exp<<"Time:  "<<duration << " seconds" <<'\n'; //Print to console
f2<<duration<<endl;     //Print to file
} // End test loop

f2.close();``````
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.