This code is supposed to display a menu with 6 options. create new file, display numbers, total, and average, display a sort, search for a num and tell yow how many occurrences it had, append random numbers, and display largest.
It runs and does MOST of what it is supposed to do but I just CANNOT get the searchNum function to search for the number entered.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
//Function Prototypes
void menu();
string createFile();
void displayNumTotalAverage(string myFileName);
void displaySortedNums(string myFileName);
void searchNum(string myFileName);
void displayLargestNum(string myFileName);
void appendRandomNum(string myFileName);
int main()
{
int choice = 0;
string myFileName = "";
do
{
cout << "** MENU **" << endl << endl;
cout << "Current Data File: ";
cout << fixed << setprecision(2) << showpoint;
menu();
cin >> choice;
while (choice < 1 || choice > 7)
{
cout << "Menu Choice: ";
cin >> choice;
cout << endl;
}
switch (choice)
{
case 1:
myFileName = createFile();
break;
case 2:
displayNumTotalAverage(myFileName);
break;
case 3:
displaySortedNums(myFileName);
break;
case 4:
searchNum(myFileName);
break;
case 5:
displayLargestNum(myFileName);
break;
case 6:
appendRandomNum(myFileName);
break;
}
} while (choice != 7);
system("PAUSE");
return 0;
}
void menu()
{
cout << "\n\n(1) Select / create data file(.txt file extension will be added automatically)\n"
<< "(2) Display all numbers, total, and average\n(3) Display all numbers sorted\n(4) "
<< "Search for a number and display how many times it occurs\n(5) Display the largest number\n"
<< "(6) Append a random number(s)\n(7) Exit the program\n\nMenu Choice:";
}
string createFile()
{
string myFileName;
ifstream inFile;
cout << "\nName of data file: ";
cin >> myFileName;
inFile.open(myFileName);
if (inFile)
{
cout << myFileName;
}
else
{
cout << "\nFile not found, creating file.\n\n";
ofstream outFile;
outFile.open(myFileName + ".txt");
}
system("PAUSE");
return myFileName;
}
void displayNumTotalAverage(string myFileName)
{
ifstream inFile;
const int SIZE = 50;
int num[SIZE];
int count = 0;
int total = 0;
double average = 0;
inFile.open(myFileName + ".txt");
while (!inFile)
cout << "\nData File is empty" << endl << endl;
while (count < SIZE && inFile >> num[count])
count++;
inFile.close();
for (int index = 0; index < count; index++)
{
cout << num[index] << endl;
total += num[index];
}
average = (float)total / count;
cout << endl << "Total : " << total << endl << endl;
cout << "Average: " << average << endl << endl;
cout << "File Successfully Read" << endl << endl;
system("PAUSE");
return;
}
void displaySortedNums(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
if(inFile.good())
{
const int SIZE = 50;
int num[SIZE]; int counter = 0;
while (counter < SIZE && inFile >> num[counter])
counter++;
inFile.close();
for(int idx1 = 0; idx1 < counter; ++idx1)
for(int idx2 = idx1; idx2 < counter; ++idx2)
if(num[idx1] > num[idx2])
{
int tmp = num[idx1];
num[idx1] = num[idx2];
num[idx2] = tmp;
}
for (int i = 0; i < counter; i++)
{
cout << num[i] << endl;
}
cout << endl;
}
system("PAUSE");
return;
}
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
const int SIZE = 50;
int num[SIZE];
bool found = false;
int position = -1;
int index = 0;
int userNum = 0;
int counter = 0;
int numCount = 0;
cout << "Search Number: ";
cin >> userNum;
cout << endl << endl;
while (index < SIZE && !found)
{
if (num[index] == userNum)
{
found = true;
position = index;
numCount++;
}
index++;
}
cout << userNum << " occurs " << numCount << " times ";
cout << "File Successfully Read\n\n";
system("PAUSE");
return;
}
void displayLargestNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
const int SIZE = 50;
int nums[SIZE];
int count = 0;
int highest;
while (count < SIZE && inFile >> nums[count])
count++;
highest = nums[0];
for (int i = 0; i < SIZE; i++)
{
if (nums[i] > highest)
highest = nums[count];
}
cout << "\nLargest Number: " << highest << endl << "File Successfully Read" << endl << endl;
}
void appendRandomNum(string myFileName)
{
cout << "i am in the appendRandomNum function - option 6" << endl;
int num = 0;
int count = 0;
ofstream outFile;
outFile.open(myFileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
system("PAUSE");
return;
}
Can anyone please help with this?
I can see 2 problems in searchNum function:
The file is opened but num array is not populated with the file content
numCount will always return either 0 or 1. Remove 'found' boolean variable altogether and it will then return the correct numCount value.
Here are some important rules they never seem to teach in programming courses: start with something small and simple that works, add complexity a little at a time, and develop new functionality in isolation.
Suppose you have the rest of the code working perfectly, and you can produce a file called nums.txt that looks like this:
7
9
3
8
0
2
4
8
3
9
Now you want to develop and test the searchNum function. So you write a main function like this:
int main()
{
string myFileName = "nums";
searchNum(myFileName);
system("PAUSE");
return 0;
}
Then a searchNum function:
void searchNum(string myFileName)
{
}
You compile and run this, it does nothing, so far so good.
Now have it open the file, read the first number and display it:
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
int num;
inFile >> num;
cout << num << endl;
}
So far so good. Now iterate through the whole file:
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
int num;
while(inFile >> num)
{
cout << num << endl;
}
}
So far so good. Now count the 8's:
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
int num;
int count = 0;
while(inFile >> num)
{
cout << num << endl;
if(num == 8)
++count;
}
}
You get the idea. Using this approach you'll get clean working code, and you'll get it faster than by trying to write it all and then fix all the bugs.
A couple of things I noticed also in searchNum
inFile.open(myFileName + "txt"); should be inFile.open(myFileName + ".txt");, a dot is missing from the suffix.
Read the rest of the answers and get acquainted with the debugger it will save you a lot of time and frustration.
Here is your code sample with the needed corrections. Keep up the good work and invest some time for the use of a debugger.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
//Function Prototypes
void menu();
string createFile();
void displayNumTotalAverage(string myFileName);
void displaySortedNums(string myFileName);
void searchNum(string myFileName);
void displayLargestNum(string myFileName);
void appendRandomNum(string myFileName);
int main()
{
int choice = 0;
string myFileName = "";
do
{
cout << "** MENU **" << endl << endl;
cout << "Current Data File: " << myFileName << (!myFileName.empty() ? ".txt" : "");
cout << fixed << setprecision(2) << showpoint;
menu();
cin >> choice;
while (choice < 1 || choice > 7)
{
cout << "Menu Choice: ";
cin >> choice;
cout << endl;
}
switch (choice)
{
case 1:
myFileName = createFile();
break;
case 2:
displayNumTotalAverage(myFileName);
break;
case 3:
displaySortedNums(myFileName);
break;
case 4:
searchNum(myFileName);
break;
case 5:
displayLargestNum(myFileName);
break;
case 6:
appendRandomNum(myFileName);
break;
}
} while (choice != 7);
cin.get();
return 0;
}
void menu()
{
cout << "\n\n(1) Select / create data file(.txt file extension will be added automatically)\n"
<< "(2) Display all numbers, total, and average\n(3) Display all numbers sorted\n(4) "
<< "Search for a number and display how many times it occurs\n(5) Display the largest number\n"
<< "(6) Append a random number(s)\n(7) Exit the program\n\nMenu Choice:";
}
string createFile()
{
string myFileName;
ifstream inFile;
cout << "\nName of data file: ";
cin >> myFileName;
inFile.open(myFileName + ".txt", std::ifstream::in);
if (inFile)
{
cout << myFileName;
}
else
{
cout << "\nFile not found, creating file.\n\n";
ofstream outFile;
outFile.open(myFileName + ".txt");
outFile.close();
}
cin.get();
return myFileName;
}
void displayNumTotalAverage(string myFileName)
{
ifstream inFile;
const int SIZE = 50;
int num[SIZE];
int count = 0;
int total = 0;
double average = 0;
inFile.open(myFileName + ".txt");
while (!inFile)
cout << "\nData File is empty" << endl << endl;
while (count < SIZE && inFile >> num[count])
count++;
inFile.close();
for (int index = 0; index < count; index++)
{
cout << num[index] << endl;
total += num[index];
}
average = (float)total / count;
cout << endl << "Total : " << total << endl << endl;
cout << "Average: " << average << endl << endl;
cout << "File Successfully Read" << endl << endl;
cin.get();
return;
}
void displaySortedNums(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
if(inFile.good())
{
const int SIZE = 50;
int num[SIZE]; int counter = 0;
while (counter < SIZE && inFile >> num[counter])
counter++;
inFile.close();
for(int idx1 = 0; idx1 < counter; ++idx1)
for(int idx2 = idx1; idx2 < counter; ++idx2)
if(num[idx1] > num[idx2])
{
int tmp = num[idx1];
num[idx1] = num[idx2];
num[idx2] = tmp;
}
for (int i = 0; i < counter; i++)
{
cout << num[i] << endl;
}
cout << endl;
}
cin.get();
return;
}
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
const int SIZE = 50;
int num[SIZE];
int position = -1;
int index = 0;
int userNum = 0;
int counter = 0;
int numCount = 0;
cout << "Search Number: ";
cin >> userNum;
cout << endl << endl;
// Fill num array with inFile numbers.
while (counter < SIZE && inFile >> num[counter++]);
while (index < SIZE)
{
if (num[index] == userNum)
{
position = index;
numCount++;
}
index++;
}
cout << userNum << " occurs " << numCount << " times ";
cout << "File Successfully Read\n\n";
cin.get();
return;
}
void displayLargestNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
const int SIZE = 50;
int nums[SIZE];
int count = 0;
int highest;
while (count < SIZE && inFile >> nums[count])
count++;
highest = nums[0];
for (int i = 0; i < SIZE; i++)
{
if (nums[i] > highest)
highest = nums[count];
}
cout << "\nLargest Number: " << highest << endl << "File Successfully Read" << endl << endl;
}
void appendRandomNum(string myFileName)
{
cout << "i am in the appendRandomNum function - option 6" << endl;
int count = 0;
ofstream outFile;
outFile.open(myFileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
cin.get();
return;
}
Related
I've been learning to program for a few months now and I've been working on a program to manage student data. Here's the code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <stdio.h>
using namespace std;
class Student
{
private:
string name;
string course;
int section;
int grade;
public:
void calcgrade();
void getData();
void showData();
};
void Student::calcgrade()
{
if (grade >= 90)
grade = 'A';
else if (grade >= 80)
grade = 'B';
else if (grade >= 70)
grade = 'C';
else if (grade >= 60)
grade = 'D';
else
grade = 'F';
}
void Student::getData()
{
cout << "Enter the name of the student: ";
cin.ignore();
getline(cin, name);
cout << "Enter the course: ";
cin >> course;
cout << "Enter the section: ";
cin >> section;
cout << "Enter the grade received: ";
cin >> grade;
calcgrade();
}
void Student::showData()
{
cout << ".......Student Information......" << endl;
cout << "Student Name: " << name << endl;
cout << "Course: " << course << endl;
cout << "Section: " << section << endl;
cout << "Grade: " << grade << endl;
cout << endl;
}
void addData()
{
Student st;
ofstream fout;
fout.open("Student.data", ios::binary | ios::out |
ios::app);
st.getData();
fout.write((char*)& st, sizeof(st));
fout.close();
cout << "Data Successfully Saved to File." << endl;
}
void displayData()
{
Student st;
ifstream file;
file.open("Student.data", ios::in | ios::binary);
if (file.is_open())
{
while (file.read((char*)& st, sizeof(st)))
{
st.showData();
}
cout << "Finished Reading Data From File." <<
endl;
}
else
{
cout << "Unable to open file" << endl;
}
file.close();
}
void searchData()
{
Student st;
ifstream file;
file.open("Student.data", ios::in | ios::binary);
string search;
cout << "Please enter the first name of a student to search for: ";
cin >> search;
bool isFound = 0;
while (file.read((char*)& st, sizeof(st)))
{
string temp = " ";
getline(file, temp);
for (int i = 0; i < search.size(); i++)
{
if (temp[i] == search[i])
isFound = 1;
else
{
isFound = 0;
break;
}
}
if (isFound)
{
cout << "The name " << search << " was found in the database." << endl;
break;
}
}
if (file.read((char*)& st, sizeof(st)) && (!isFound))
{
cout << "Name not found." << endl;
}
file.close();
}
void modifyData()
{
Student st;
string stname;
bool isFound = 0;
int pos;
fstream file;
file.open("Student.data", ios::in | ios::out | ios::binary);
cout << "Enter the name of a student whose data you want to modify: ";
cin >> stname;
while (file.read((char*)& st, sizeof(st)))
{
string temp = " ";
getline(file, temp);
for (int i = 0; i < stname.size(); i++)
{
if (temp[i] == stname[i])
isFound = 1;
else
{
isFound = 0;
break;
}
}
if (isFound)
{
pos = file.tellg();
cout << "Current Data" << endl;
st.showData();
cout << "Modified Data" << endl;
st.getData();
file.seekg(pos - sizeof(st));
file.write((char*)& st, sizeof(st));
}
}
if (file.read((char*)& st, sizeof(st)) && (!isFound))
{
cout << "Name not found." << endl;
}
file.close();
}
void deleteData()
{
Student st;
string stname;
bool isFound = 0;
ifstream file;
ofstream fout;
file.open("Student.data", ios::in | ios::binary);
fout.open("Temporary.data", ios::out | ios::app | ios::binary);
cout << "Enter the name of a student whose data you want to delete: ";
cin >> stname;
while (file.read((char*)& st, sizeof(st)))
{
string temp = " ";
getline(file, temp);
for (int i = 0; i < stname.size(); i++)
{
if (temp[i] == stname[i])
isFound = 1;
else
{
isFound = 0;
break;
}
}
if (isFound)
{
cout << "Bleh" << endl;
fout.write((char*)& st, sizeof(st));
}
}
if (file.read((char*)& st, sizeof(st)) && (!isFound))
{
cout << "Name not found." << endl;
}
fout.close();
file.close();
remove("Student.data");
rename("Temporary.data", "Student.data");
}
void printData()
{
ifstream file;
file.open("Student.data", ios::in | ios::binary);
if (file.is_open())
{
cout << file.rdbuf();
}
file.close();
}
int main()
{
int num;
do
{
cout << "...............STUDENT MANAGEMENT SYSTEM..............\n";
cout << "======================================== ==============\n";
cout << "0. Close Program. " << endl;
cout << "1. Add Data. " << endl;
cout << "2. List Data. " << endl;
cout << "3. Modify Data. " << endl;
cout << "4. Search For Data. " << endl;
cout << "5. Print Data. " << endl;
cout << "6. Delete Data. " << endl;
cout << "Choose an option: ";
cin >> num;
if (num == 1)
{
addData();
}
else if (num == 2)
{
displayData();
}
else if (num == 3)
{
modifyData();
}
else if (num == 4)
{
searchData();
}
else if (num == 5)
{
printData();
}
else if (num == 6)
{
deleteData();
}
} while (num > 0);
return 0;
}
Ideally, when the program runs, the user chooses an option, with different function calls depending on the number entered. The Add Data option works fine, but when choosing others, such as List Data or Search Data, I run into an error such as: Unhandled exception thrown: read access violation. _Pnext was 0x10A6A04.
Code in xmemory:
inline void _Container_base12::_Orphan_all() noexcept {
#if _ITERATOR_DEBUG_LEVEL == 2
if (_Myproxy != nullptr) { // proxy allocated, drain it
_Lockit _Lock(_LOCK_DEBUG);
for (_Iterator_base12** _Pnext = &_Myproxy->_Myfirstiter; *_Pnext != nullptr;
*_Pnext = (*_Pnext)->_Mynextiter) {
(*_Pnext)->_Myproxy = nullptr;
}
_Myproxy->_Myfirstiter = nullptr;
}
Given there are no obvious errors in the code, I'd like a little help in figuring out what I've done wrong.
Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}
You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.
So what I am trying to do is put a random number generator from one through ten into an array that has 50 elements and then put that into a text file. My problem is that the code I have written for the code and generator has an error and I can't wrap my head around how to get it into a text file.
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include<fstream>
using namespace std;
void menu();
string createFile();
void displayNumTotalAverage(string);
void displaySortedNums();
void SearchNum();
void displayLargestNum();
void appendRandomNum(string);
void exit();
void CreateFile();
void printFunc(int[]);
void fillFunc(int[]);
int main()
{
menu();
string FileName;
//createFile();
//makeRandomNum();
system("pause");
return 0;
}
void menu()
{
int choice;
string FileName;
do
{
//program output
cout << "** MENU **" << endl << endl;
cout << "Curret Data File: " << endl << endl;
cout << "(1) Select / create data file (.txt file extention will be added automaticly)" << endl;
cout << "(2) Display all numbers, total and average" << endl;
cout << "(3) Display all numbers sorted" << endl;
cout << "(4) search for a number and display how many times it occurs" << endl;
cout << "(5) display the largest number" << endl;
cout << "(6) Append a random number(s)" << endl;
cout << "(7) Exit the program" << endl << endl;
//user input
cout << "Menu Choice: ";
cin >> choice;
while (choice > 7 || choice < 1)
{
cout << "Menu Choice: ";
cin >> choice;
}
switch (choice)
{
case 1:
cout << "Choice 1";
createFile();
break;
case 2:
cout << "Choice 2";
displayNumTotalAverage(FileName.c_str());
break;
case 3:
cout << "Choice 3";
break;
case 4:
cout << "Choice 4";
break;
case 5:
cout << "Choice 5";
break;
case 6:
cout << "Choice 6";
appendRandomNum(FileName.c_str());
break;
}
} while (choice != 7);
}
string createFile()<----------------------------------------------------(this)
{
cout << "Create File - Option 1" << endl;
string FileName;
ifstream inFile;
cout << "Name of data file: ";
cin >> FileName;
FileName = "C:\\Users\Wizard\Libraries\Documents\Final Project" + FileName;
inFile.open(FileName + ".txt");
if (inFile)
{
cout << FileName;
}
else
cout << "File not found, creating file.";
system("PAUSE");
return FileName;
}
void displayNumTotalAverage(string FileName)
{
ifstream inFile;
cout << "Display Number Total Average - Option 2" << endl << endl << endl;
inFile.open("C:\\Users\Wizard\Libraries\Documents\Final Project" + FileName + ".txt");
int num;
int total;
cout << "Display Number Total Average function" << FileName;
double average;
bool containsNum = false;
inFile.open(FileName + ".txt");
if (inFile)
{
while (inFile >> num)
{
cout << num << endl;
}
inFile.close();
}
else
{
cout << "Error opening file" << FileName << "." << endl;
}
system("PAUSE");
return;
}
void displaySortedNums()
{
cout << "I AM THE displaySortedNums Function - Option 3" << endl;
system("PAUSE");
return;
}
void searchNum()
{
cout << " I am the searchNum function - option 4" << endl;
system("PAUSE");
return;
}
void displayLargestNum()
{
cout << "I am the displayLargestNum Function - option 5" << endl;
system("PAUSE");
return;
}
void appendRandomNum(string FileName)
{
cout << "i am in the appendRandomNum function - option 6" << endl;
int num = 0;
int count = 0;
ofstream outFile;
outFile.open(FileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
system("PAUSE");
return;
}
void exit()
{
cout << " I am the exit function - option 7" << endl;
system("PAUSE");
return;
}
void CreateFile()<-----------(and this)
{
int random[50]; //Random Numbers
srand((unsigned)time(NULL));
fillFunc(random);
printFunc(random);
return;
}
void fillFunc(int arr[])
{
for (int i = 0; i < 50; i++)
{
arr[i] = 1 + rand() % 10;
}
}
void printFunc(int arr[])
{
ofstream fout("C:\\Users\Wizard\Libraries\Documents\Final Project");
if (fout.is_open()){
for (int i = 0; i < 50; i++)
{
fout << arr[i] << std::endl;
}
}
}
Assuming you have the tmp folder in your project directory, and pretending the path is: C:\Project\tmp\. This file fails to open: ofstream fout("/tmp/nums.txt");
The first slash is an error. It's as if you tried to open C:\Project\\tmp\.
If you are using Windows, it's like if you changed directory to C:\Project in command promt and then used the command cd \tmp which would result in:
The system cannot find the path specified.
Therefore, omit the first slash and let it be: ofstream fout("tmp/nums.txt"); and it will work. (I assume you're including <fstream> and that you're using the namespace std.)
there are several issues in your original code:
1) you didn't create any text file to output. Are you trying to output using ">" ?
2) you are generating 49 numbers only. To get 50, you need start from 0 instead 1. (int i=0; )
3) You don't have any delimiter in your output. How do you expect to use them?
change your printFunc to something like this:
ofstream fout ("/tmp/nums.txt");
if(fout.is_open() ){
for (int i = 0; i < 50; i++)
{
fout << arr[i] << std::endl;
}
Include fstream #include <fstream>
In printFunc change:
ofstream fout("/tmp/nums.txt");
to
ofstream fout("folder/inner_folder/file.txt", ofstream::out);
The second parameter is the mode for the file. ofstream::out means write access (which is always set for ofstream objects).
At the end of the function close the stream like so:
fout.close();
For reference: http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
For my code I need to search for the largest number in the array, add up and get the averages of the numbers inside of it, and search for the largest number in it. my code has the basic idea of what i want to do for each.
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include<fstream>
using namespace std;
void menu();
string createFile();
void displayNumTotalAverage(string);
void displaySortedNums();
void BubbleSort();
void SearchNum();
void displayLargestNum();
void appendRandomNum(string);
void exit();
void CreateFile();
void printFunc(int[]);
void fillFunc(int[]);
int main()
{
menu();
string FileName;
createFile();
CreateFile();
system("pause");
return 0;
}
void menu()
{
int choice;
string FileName;
do
{
//program output
cout << "** MENU **" << endl << endl;
cout << "Curret Data File: " << endl << endl;
cout << "(1) Select / create data file (.txt file extention will be added automaticly)" << endl;
cout << "(2) Display all numbers, total and average" << endl;
cout << "(3) Display all numbers sorted" << endl;
cout << "(4) search for a number and display how many times it occurs" << endl;
cout << "(5) display the largest number" << endl;
cout << "(6) Append a random number(s)" << endl;
cout << "(7) Exit the program" << endl << endl;
//user input
cout << "Menu Choice: ";
cin >> choice;
while (choice > 7 || choice < 1)
{
cout << "Menu Choice: ";
cin >> choice;
}
switch (choice)
{
case 1:
cout << "\nChoice 1" << endl << endl;
createFile();
break;
case 2:
cout << "\nChoice 2" << endl << endl;
displayNumTotalAverage(FileName.c_str());
break;
case 3:
cout << "\nChoice 3" << endl << endl;
break;
case 4:
cout << "\nChoice 4" << endl << endl;
break;
case 5:
cout << "\nChoice 5" << endl << endl;
break;
case 6:
cout << "\nChoice 6" << endl << endl;
appendRandomNum(FileName.c_str());
break;
case 7:
exit();
break;
}
} while (choice != 7);
}
string createFile()
{
string FileName;
ifstream inFile;
cout << "Name of data file: ";
cin >> FileName;
FileName = "C:\\Users\Wizard\Libraries\Documents\Final Project.txt" + FileName;
inFile.open(FileName + ".txt");
if (inFile)
{
cout << FileName;
}
else
cout << "File not found, creating file."<<endl;
system("PAUSE");
return FileName;
}
void displayNumTotalAverage(string FileName)
{
ifstream inFile;
cout << "Display Number Total Average - Option 2" << endl << endl << endl;
inFile.open("C:\\Users\Wizard\Libraries\Documents\Final Project" + FileName + ".txt");
int num;
int total=0;
cout << "Display Number Total Average function" << FileName << endl;
double average;
bool containsNum = false;
inFile.open(FileName + ".txt");
if (inFile)
{
while (inFile >> num)
{
cout << num << endl;
}
inFile.close();
}
else
{
cout << "Error opening file" << FileName << "." << endl;
}
system("PAUSE");
return;
}
void displaySortedNums(int arr[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (arr[count]>arr[count + 1])
{
temp = arr[count];
arr[count] = arr[count + 1];
swap = true;
}
}
} while (swap);
system("PAUSE");
return;
}
void searchNum()
{
cout << " I am the searchNum function - option 4" << endl;
system("PAUSE");
return;
}
void displayLargestNum(int arr[], int numElems, int value)
{
{
int index = 0;
int position = -1;
bool found = false;
while (index < numElems && !found)
{
if (arr[index] == value)
found = true;
position = index;
}
index++;
return;
}
system("PAUSE");
return;
}
void appendRandomNum(string FileName)
{
int num = 0;
int count = 0;
ofstream outFile;
outFile.open(FileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
system("PAUSE");
return;
}
void exit()
{
std::exit(0);
system("PAUSE");
return;
}
void CreateFile()
{
int random[50]; //Random Numbers
srand((unsigned)time(NULL));
fillFunc(random);
printFunc(random);
return;
}
void fillFunc(int arr[])
{
for (int i = 0; i < 50; i++)
{
arr[i] = 1 + rand() % 10;
}
}
void printFunc(int arr[])
{
ofstream fout("C:\\Users\Wizard\Libraries\Documents\Final Project");
if (fout.is_open()){
for (int i = 0; i < 50; i++)
{
fout << arr[i] << std::endl;
}
}
}
If your array name is arr and size is n.
Search the largest number as follows:
int max = arr[0];
for ( int i = 1; i < n; i++ )
max = (arr[i] > max ) ? arr[i] : max;
Finally, max is the largest number.
To add up the array:
int sum = 0;
for ( int i = 0; i < n; i++ )
sum += arr[i];
so you can adopt a pet (kind of buggy right now since it doesn't read in the value)
In the file i'll see it turn into a 1 from a 0; which means it is true. and therefore it should say adopted.
is this the correct way to read in a bool? The problem is in the read function, my problem is that the
read >>
#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
using namespace std;
const int TEMP_SIZE = 250;
struct animal
{
char *name;
char *breed;
float age;
float weight;
char *desc;
bool adopted;
//we generate this
int ID;
};
struct family
{
char *host;
char *address;
int numDogs;
};
class petAdoption
{
public:
//petAdoption();
//~petAdoption();
void enroll(animal pet[], int & count);
void read(animal pet[], int & count);
void display(animal pet[], int & count);
void adoptPet(animal pet[], int & count);
void getNum(int & count);
};
void petAdoption::enroll(animal pet[], int & count)
{
//name Dynamic array 1;
char temp[TEMP_SIZE];
cout << "Please your pet's name: ";
cin.get(temp, TEMP_SIZE);
cin.ignore(100, '\n');
pet[count-1].name = new char[strlen(temp)];
strcpy(pet[count-1].name, temp);
//breed Dynamic array 2;
cout << "Please your pet's breed: ";
cin.get(temp, TEMP_SIZE);
cin.ignore(100, '\n');
pet[count-1].breed = new char[strlen(temp)];
strcpy(pet[count-1].breed, temp);
//desc Dynamic array 3;
cout << "Please a desc of your pet: ";
cin.get(temp, TEMP_SIZE);
cin.ignore(100, '\n');
pet[count-1].desc = new char[strlen(temp)];
strcpy(pet[count-1].desc, temp);
//not adopted
pet[count-1].adopted = false;
ofstream write;
write.open("pets.txt", ios::app);
write << pet[count-1].name << '\n';
write.close();
write.open(pet[count-1].name);
write << pet[count-1].name << '\n'
<< pet[count-1].breed << '\n'
<< pet[count-1].desc << '\n'
<< pet[count-1].adopted << '\n';
write.close();
}
//This method basically, allocates memory for the array.
void petAdoption::getNum(int & count)
{
ifstream read;
char temp[TEMP_SIZE];
read.open("pets.txt");
if(!read)
{
cout << "error 1" << endl;
count = 1;
}
else{
while(!read.eof())
{
read.getline(temp, TEMP_SIZE);
count = ++count;
}
}
read.close();
}
void petAdoption::read(animal pet[], int & count)
{
ifstream read;
char temp[TEMP_SIZE];
//read in the names
int k = 0;
read.open("pets.txt");
if(!read)
{
cout << "There's No pets.txt file! (Ignore this!)" <<endl;
}
else
{
while(!read.eof())
{
read.getline(temp, TEMP_SIZE);
pet[k].name = new char[strlen(temp)+1];
strcpy(pet[k].name, temp);
++k;
}
}
read.close();
for (int i = 0; i < count-1; ++i)
{
read.open(pet[i].name);
if(!read)
{
cout << "error 2" << endl;
}
else{
while(!read.eof())
{
//name
read.getline(temp, TEMP_SIZE);
pet[i].name = new char[strlen(temp)+1];
strcpy(pet[i].name, temp);
//breed
read.getline(temp, TEMP_SIZE);
pet[i].breed = new char[strlen(temp)+1];
strcpy(pet[i].breed, temp);
//desc
read.getline(temp, TEMP_SIZE);
read.ignore(100, '\n');
pet[i].desc = new char[strlen(temp)+1];
strcpy(pet[i].desc, temp);
read >> pet[i].adopted;
cout << i << endl;
}
}
read.close();
}
}
void petAdoption::display(animal pet[], int & count)
{
for (int i = 0; i < count-1; ++i){
cout << "Pet id = " << i << '\n' << endl;
cout << pet[i].name << '\n' << pet[i].breed << '\n' << pet[i].desc << '\n';
cout << pet[i].adopted << endl;
if (pet[i].adopted == false){
cout << "Not adopted" << '\n' << endl;
}
if (pet[i].adopted == true){
cout << "Adopted" << '\n' << endl;
}
}
}
void petAdoption::adoptPet(animal pet[], int & count)
{
int adoptID;
cout << "Which pet would you like to adopt? (Please enter the ID, EG: 2 or 5): ";
cin >> adoptID;
cin.ignore(100, '\n');
pet[adoptID].adopted = true;
cout << pet[adoptID].adopted << endl;
ofstream write;
for (int i = 0; i < count; ++i){
write.open(pet[i].name);
write << pet[i].name << '\n'
<< pet[i].breed << '\n'
<< pet[i].desc << '\n'
<< pet[i].adopted << '\n';
write.close();
}
}
int main()
{
//When starting the program, we read in from the text files first
//and then we count how many animals we have had in the shelter
//and we use that as a base to dynamically allocate the structs
petAdoption adopt;
char again;
int choice;
do {
int count = 0;
adopt.getNum(count);
animal *pet;
pet = new animal[count];
adopt.read(pet, count);
cout << "~~~~~~~~~~~~~~~~~~MENU~~~~~~~~~~~~~~~~~~" << endl;
cout << "1) Enroll a pet" << endl;
cout << "2) Display pets" << endl;
cout << "3) Adopt a pet" << endl;
cout << "Please make your selection (1-3): ";
cin >> choice;
cin.ignore(100,'\n');
if (1 == choice){
adopt.read(pet, count);
adopt.enroll(pet, count);
}
if (2 == choice){
adopt.read(pet, count);
adopt.display(pet, count);
}
if (3 == choice){
adopt.read(pet, count);
adopt.adoptPet(pet, count);
}
cout << "Would you like to try again? (y/n): ";
cin >> again;
cin.ignore(100,'\n');
} while ('Y' == toupper(again));
}
It seems problem is in your logic, i have fixed few things in you code and it is working take a look:
Things I fixed are:
- enroll(animal pet[], int & count)
- getNum(int & count)
- read(animal pet[], int & count)
- display(animal pet[], int & count)
#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
using namespace std;
const int TEMP_SIZE = 250;
struct animal
{
char *name;
char *breed;
float age;
float weight;
char *desc;
bool adopted;
//we generate this
int ID;
};
struct family
{
char *host;
char *address;
int numDogs;
};
class petAdoption
{
public:
//petAdoption();
//~petAdoption();
void enroll(animal pet[], int & count);
void read(animal pet[], int & count);
void display(animal pet[], int & count);
void adoptPet(animal pet[], int & count);
void getNum(int & count);
};
void petAdoption::enroll(animal pet[], int & count)
{
//name Dynamic array 1;
char temp[TEMP_SIZE];
cout << "Please your pet's name: ";
cin.get(temp, TEMP_SIZE);
cin.ignore(100, '\n');
pet[count-1].name = new char[strlen(temp)];
strcpy(pet[count-1].name, temp);
//breed Dynamic array 2;
cout << "Please your pet's breed: ";
cin.get(temp, TEMP_SIZE);
cin.ignore(100, '\n');
pet[count-1].breed = new char[strlen(temp)];
strcpy(pet[count-1].breed, temp);
//desc Dynamic array 3;
cout << "Please a desc of your pet: ";
cin.get(temp, TEMP_SIZE);
cin.ignore(100, '\n');
pet[count-1].desc = new char[strlen(temp)];
strcpy(pet[count-1].desc, temp);
//not adopted
pet[count-1].adopted = false;
ofstream write;
write.open("pets.txt", ios::beg | ios::app);
write << pet[count-1].name << '\n';
write << pet[count-1].breed << '\n';
write << pet[count-1].desc << '\n';
write << pet[count-1].adopted << '\n';
write.close();
}
//This method basically, allocates memory for the array.
void petAdoption::getNum(int & count)
{
ifstream read;
char temp[TEMP_SIZE];
int count_temp = 0;
read.open("pets.txt");
while(!read.eof())
{
read.getline(temp, TEMP_SIZE);
count_temp++;
if (count_temp == 4){
count++;
count_temp = 0;
}
}
read.close();
}
void petAdoption::read(animal pet[], int & count)
{
ifstream read;
char temp[TEMP_SIZE];
//read in the names
int k = 0, i =0;
read.open("pets.txt");
while(read.good()){
if (i < count){
//name
read.getline(temp, TEMP_SIZE);
pet[i].name = new char[strlen(temp)+1];
strcpy(pet[i].name, temp);
//breed
read.getline(temp, TEMP_SIZE);
pet[i].breed = new char[strlen(temp)+1];
strcpy(pet[i].breed, temp);
//desc
read.getline(temp, TEMP_SIZE);
pet[i].desc = new char[strlen(temp)+1];
strcpy(pet[i].desc, temp);
read.getline(temp, TEMP_SIZE);
if (strcmp(temp,"0") == 0){
pet[i].adopted = true;
}else{
pet[i].adopted = false;
}
}else{
cout << i << endl;
break;
}
i++;
}
read.close();
}
void petAdoption::display(animal pet[], int & count)
{
for (int i = 0; i < count; i++){
cout << "Pet id = " << i << '\n' << endl;
cout << pet[i].name << '\n' << pet[i].breed << '\n' << pet[i].desc << '\n';
cout << pet[i].adopted << endl;
if (pet[i].adopted == false){
cout << "Not adopted" << '\n' << endl;
}else{
cout << "Adopted" << '\n' << endl;
}
}
}
void petAdoption::adoptPet(animal pet[], int & count)
{
int adoptID;
cout << "Which pet would you like to adopt? (Please enter the ID, EG: 2 or 5): ";
cin >> adoptID;
cin.ignore(100, '\n');
pet[adoptID].adopted = true;
cout << pet[adoptID].adopted << endl;
ofstream write;
write.open("pets.txt", ios::beg);
for (int i = 0; i < count; ++i){
write << pet[i].name << '\n'
<< pet[i].breed << '\n'
<< pet[i].desc << '\n'
<< pet[i].adopted<<'\n';
}
write.close();
}