#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <ctime>
#include <vector>
using namespace std;
bool fileCheck(const char *filename)
{
ifstream ifile("item.txt");
return ifile;
}
int show(int p)
{
srand( time(NULL) );
int random_integer;
random_integer = ( rand ( ) % p ) + 1;
return random_integer;
}
int main () {
SetConsoleTitle("Random Item Generator");
//Menu
cout << "Please select an option from the menu below" << endl;
cout << endl;
cout << " -Menu List- " << endl;
cout << endl;
cout << "1. Add Item" << endl;
cout << "2. Display All Items" << endl;
cout << "3. Display Random Item" << endl;
cout << "4. Quit" << endl;
int a = 0;
bool firstTime = true;
while (a != 4) {
if (firstTime == false) {
cout << endl;
cout << "Please select another option from the menu above" << endl;
}
cin >> a;
if (a == 1) {
if (fileCheck("item.txt") == false) {
string itemName;
cout << "Please type the item that you would like to add." << endl;
ofstream myfile;
myfile.open ("item.txt");
cin >> itemName;
myfile << itemName << endl;
myfile.close();
}
else {
string itemName;
cout << "Please type the item that you would like to add. (Please use an underscore in place of any spaces)" << endl;
ofstream myfile ( "item.txt", ios::app );
cin >> itemName;
myfile << itemName << endl;
myfile.close();
}
}
else if (a == 2) {
string fileData;
ifstream itemFile ("item.txt");
if (itemFile.is_open()) {
cout << " -List of Items- " << endl;
cout << endl;
while (! itemFile.eof() ) {
getline (itemFile,fileData);
cout << fileData << endl;
}
itemFile.close();
}
else {
cout << "Unable to open file" << endl;
}
}
else if (a == 3) {
ifstream itemFile ("item.txt");
string line;
vector<string> lines;
int counter;
while (! itemFile.eof() ) {
getline(itemFile,line, '\n');
lines.push_back( line );
counter++;
}
cout << "Random Item: " << lines[show( counter )] << endl;
itemFile.close();
}
firstTime = false;
}
return 0;
}
This program that I have been writing will output a menu to the user, let the user pick from the menu and then depending on the option give or take information from the user. I was using a switch instead of if, elseif statements, but an error came up after I wrote the second case. I decided that it would be less of a hassle to just write it like this. What I am having trouble with is the vector statement under "else if (a == 3) {}". It will output the randomized item from the list, but only part of the time. I will run it other times and it will run, but as soon as I hit the 3 to select from the menu it tells me that windows has discovered an error, and then it will close my program soon after. Any ideas?
Thank you,
Derek