Hello, I am working on the following exercise to build my C++ skills:
"Write a program that will generate 1000 random numbers (all of which are between 10 and 20), and then write all of the even numbers out of that list of randoms to a new file called “myEvenRandoms.txt”."
This is the code I have so far. I'm aware that I have to use ofstream, but no matter what I tried I couldn't get it to work.
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fstream>
int main() // main *must* have return type int
// http://www.stroustrup.com/bs_faq2.html#void-main
{
std::ofstream fout( "C:/Users/Zorai/Documents/numbers.txt" );
if( !fout.is_open() ) std::cerr << "error opening file!\n" ;
else
{
// consider using facilities in <random>
// http://en.cppreference.com/w/cpp/numeric/random
std::srand( std::time(nullptr) ) ;
for( int i = 0; i < 1000; ++i )
{
constint number = std::rand() % 10 + 11;
if( number%2 == 0 ) fout << number << '\n' ; // if it is an even number
}
if(fout) std::cout << "numbers were written to file\n" ;
else std::cerr << "error while writing numbers to file\n" ;
}
}