I have a very easy question for you guys out there. It's been a while since I took my programming courses (switched majors) but am trying to get my feet wet again.
Objective:
I will be creating a program that will output 10 random full names (and have it be different every time the program is run). Before I complete it, I'd like some feedback on the first iteration, which just chooses random first names.
Info:
I have a file called firstnames.txt
, containing a list of 10 first names.
Premise:
I'm a beginner and I/O really throws me. I feel this is a basic enough program for me to learn from, and with your advice, I'll be able to copy/paste the same code to get a last name.
Thanks!
Here's what I have so far:
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <string> //random headers because it's been awhile :P
#include <fstream>
#include <time.h>
using namespace std;
int main()
{
//Variable declarations
int a = 0;
int randNum;
ifstream myFile;
myFile.open("firstnames.txt");
string names[10]; // holds the 10 names in the file.
string randomNames[10];// holds the randomly generated names FROM the file.
while (myFile.good())
{
getline(myFile, names[a]); // reads the names from the text file, into an array named "names[]."
a++;
}
for (int i = 0; i < 10; i++) // makes this program iterate 10 times; giving you 10 random names.
{
srand( time(NULL) ); // seed for the random number generator.
randNum = rand() % 10 + 1; // gets a random number between 1, and 10.
randomNames[i] = names[randNum];
}
for (int i = 0; i < 10; i++)
{
cout << randomNames[i] << endl; // outputs all 10 names at once.
}
myFile.close();
return EXIT_SUCCESS;
}
My firstnames.txt
looks like:
Ryan
John
Daniel
Gavin
Frank
Danielle
Lucy
Sarah
Katie
Nicole
My lastnames.txt
will look similar:
Johnson
Lewis
Walker
Robinson
Wood
Thompson
White
Watson
Jackson
Wright
(Another question I guess would be is the way I formatted the names (each name on a new line) a bit over complicated in the text file? Like would it be better/shorter to just separate each name by a space or something?)
Thanks again!