I've been trying to delete an element from my vector using fstream for a while. I made a post before about this and I applied the advice from you guys but still I'm not getting my program to delete the element of my vector.
I can creat and re write my .txt file into another one but I can't make my code to delete the element. I think I've been having problems with ios::truc or ios::out. Any suggestion ? feel free to try my code and check it out.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <fstream>
#include <stdlib.h>
using namespace std;
void Menu()
{
cout << "******************" << endl;
cout << "1 - Add student" << endl;
cout << "2 - Delete student" << endl;
cout << "3 - All students" << endl;
cout << "******************" << endl;
}
struct School
{
string Name;
string remove;
int Ages;
int Option;
};
int main()
{
School Students;
vector <string> Names;
ofstream Myfile("practiceFile.txt", ios::app);
if(!Myfile.is_open())
{
cout << "Error opening file" << endl;
}
if(Myfile.is_open())
{
Menu();
cout << endl;
cout << "Option: ";
cin >> Students.Option;
cin.ignore();
if(Students.Option == 1)
{
cout << "Enter name: ";
getline(cin, Students.Name);
Names.push_back(Students.Name);
for(int i = 0; i < Names.size(); i++)
{
Myfile << Names[i] << endl;
}
}
if(Students.Option == 2)
{
cout << "Enter name: ";
getline(cin, Students.remove);
for(int i = 0; i < Names.size(); i++)
{
if(Students.remove == Names[i])
{
auto itr = find(Names.begin(), Names.end(), Students.remove);
if(itr != Names.end())
{
Names.erase(itr);
Myfile << Names[i] << endl;
}
}
}
}
}
ofstream TempFile("practiceFile_temp.txt", ios::trunc|ios::out);
if(TempFile.is_open())
{
for(int i = 0; i < Names.size(); i++)
{
TempFile << Names[i] << endl;
}
}
TempFile.close();
Myfile.close();
remove("practiceFile.txt");
rename("practiceFile_temp.txt", "practiceFile.txt");
string line;
ifstream NewFile("practiceFile.txt", ios::in);
while(NewFile >> line)
{
if(Students.Option == 3)
{
cout << line << endl;
}
}
}
Actually, if you compile my code you won't be able to save strings into the file. But when I delete this part of my code (here below) At leats I'm able to save strings into the file but not delete them. As I said before, I think I'm not using ios::trunc|ios::out correct. Thanks!
ofstream TempFile("practiceFile_temp.txt", ios::trunc|ios::out);
if(TempFile.is_open())
{
for(int i = 0; i < Names.size(); i++)
{
TempFile << Names[i] << endl;
}
}
TempFile.close();
Myfile.close();
remove("practiceFile.txt");
rename("practiceFile_temp.txt", "practiceFile.txt");
UPDATE:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <fstream>
#include <stdlib.h>
using namespace std;
void Menu()
{
cout << "******************" << endl;
cout << "1 - Add student" << endl;
cout << "2 - Delete student" << endl;
cout << "******************" << endl;
}
struct School
{
string Name;
string remove;
int Ages;
int Option;
};
int main()
{
School Students;
vector <string> Names;
ifstream NewFile("practiceFile.txt");
string line;
while(getline(NewFile, line))
{
cout << line << endl;
}
ofstream Myfile("practiceFile.txt", ios::app);
if(!Myfile.is_open())
{
cout << "Error opening file" << endl;
}
if(Myfile.is_open())
{
Menu();
cout << endl;
cout << "Option: ";
cin >> Students.Option;
cin.ignore();
if(Students.Option == 1)
{
cout << "Enter name: ";
getline(cin, Students.Name);
Names.push_back(Students.Name);
}
if(Students.Option == 2)
{
cout << "Enter name: ";
getline(cin, Students.remove);
for(int i = 0; i < Names.size(); i++)
{
if(Students.remove == Names[i])
{
Names.erase(Names.begin() + i);
}
}
}
for(int i = 0; i < Names.size(); i++)
{
Myfile << Names[i] << endl;
}
}
ofstream TempFile("practiceFile_temp.txt", ios::trunc);
if(TempFile.is_open())
{
for(int i = 0; i < Names.size(); i++)
{
TempFile << Names[i] << endl;
}
}
TempFile.close();
Myfile.close();
remove("practiceFile.txt");
rename("practiceFile_temp.txt", "practiceFile.txt");
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I tried my best to figure this out but it was unsuccessful :C
PROBLEM
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
FULL CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <list>
#include <ctime>
using namespace std;
struct Treniruote
{
string data, laikas, vardas, pavarde, pratimai;
};
void NuskaitytiIsFailo(list<Treniruote>& treniruotes)
{
string line, word;
fstream file("planas.csv", ios::in);
if (file.is_open())
{
while (getline(file, line))
{
stringstream str(line);
Treniruote row;
if (getline(str, word, ','))
row.data = word;
if (getline(str, word, ','))
row.laikas = word;
if (getline(str, word, ','))
row.vardas = word;
if (getline(str, word, ','))
row.pavarde = word;
if (getline(str, word, ','))
row.pratimai = word;
treniruotes.push_back(row);
}
}
else
cout << "Could not open the file";
}
void rastiKlientoInfo(list<Treniruote>& treniruotes)
{
int a;
string fname, pavarde;
cout << "Write clients surname:";
cin >> pavarde;
cout << "Output to the screen press -1\n";
cout << "Output to the file press - 2\n";
cout << "Output all exercise needed to be done in a week - 3\n";
cout << "Your choice:";
cin >> a;
if (a == 2)
{
cout << "Enter the file name: ";
cin >> fname;
}
else if (a == 3)
{
cout << "Enter the file name: ";
cin >> fname;
}
else
{
}
for (Treniruote& t : treniruotes)
{
if (t.pavarde == pavarde)
{
if (a == 1)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
else if (a == 3)
{
fstream file(fname + ".csv", ios::app);
file << t.pratimai << endl;
}
else
{
fstream file(fname + ".csv", ios::app);
file << t.data << endl;
file << t.laikas << endl;
file << t.vardas << endl;
file << t.pavarde << endl;
file << t.pratimai << endl;
file << endl;
}
}
}
}
void PakeistiReiksmes(list<Treniruote>& treniruotes)
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti duomenys" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >>duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >>duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
t.vardas = t.pavarde = t.pratimai = "obolys";
}
}
}
}
void SukurtiTuscius(list<Treniruote> &treniruotes)
{
for (int i = 27; i <= 30; ++i)
{
stringstream diena;
diena << "2022.11." << i;
for (int j = 8; j <= 19; ++j)
{
stringstream valanda;
valanda << j << ":00-"<< j+1 <<":00";
Treniruote t;
t.data = diena.str();
t.laikas = valanda.str();
t.vardas = t.pavarde = t.pratimai = "nera";
treniruotes.push_back(t);
}
}
}
void ParodytiVisaTvarkarasti(list<Treniruote>& treniruotes)
{
for (Treniruote& t : treniruotes)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
void salinti_pridėti(list<Treniruote>& treniruotes)
{
}
void ProgramosPabaiga(list<Treniruote>& treniruotes)
{
fstream file("planas.csv", ios::out);
for (Treniruote& t : treniruotes)
{
file << t.data <<","<< t.laikas << "," << t.vardas << "," << t.pavarde << "," << t.pratimai;
file << endl;
}
cout << "PROGRAMA BAIGTA";
exit(0);
}
int main()
{
int choice;
bool gameOn = true;
list<Treniruote> treniruotes;
struct tm newtime;
time_t now = time(0);
localtime_s(&newtime,&now);
auto month = to_string(1 + newtime.tm_mon);
auto day = to_string(newtime.tm_mday);
auto hour = to_string(newtime.tm_hour);
auto hour_pridėta = to_string(1 + newtime.tm_hour);
//sukuria .csv faila pagal irasyta pavadinima
//string fname;
//cout << "Enter the file name: ";
//cin >> fname;
// fstream file(fname + ".csv", ios::app);
//Menu
while (gameOn != false) {
cout << "*******************************\n";
cout << " 1 - Create empty weekly plan.\n";
cout << " 2 - Show the full schedule.\n";
cout << " 3 - Read the weekly work plan.\n";
cout << " 4 - Change the schedule field information.\n";
cout << " 5 - Find the given client's full weekly workouts\n";
cout << " 7 - Exit.\n";
cout << "*******************************\n";
for (Treniruote& t : treniruotes)
{
if (t.data == "2022." + month + "." + day)
{
if (t.laikas == hour + ":00-" + hour_pridėta + ":00")
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
}
cout << "*******************************\n";
cout << " Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
SukurtiTuscius(treniruotes);
break;
case 2:
ParodytiVisaTvarkarasti(treniruotes);
break;
case 3:
NuskaitytiIsFailo(treniruotes);
break;
case 4:
PakeistiReiksmes(treniruotes);
break;
case 5:
rastiKlientoInfo(treniruotes);
break;
case 6:
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti langeli" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >> duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >> duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
}
break;
case 7:
{
ofstream file;
file.open("planas.csv", std::ofstream::out | std::ofstream::trunc);
file.close();
ProgramosPabaiga(treniruotes);
break;
}
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
return 0;
}
You must not remove items from a list while iterating through a range-based for loop. Under the hood, the loop stores a begin and end iterator of the original list, and iterate all items between them, and attempting to remove items during the loop will make end unreachable.
Instead, you could simply use std::list::remove_if to remove all elements that satisfy a certain condition:
my_list.remove_if([a, b](const auto& element){
return element.a == a && element.b == b;
};
Making a project I have to write patient database and I have a problem. Looking through guids in iтternet I dont understand how to read from file to class and how to write class into file(I realized it using common input, it is better to rewrite it).
And I dont understand how to make base constructor for char, like with int
point()
{
x=y=z=0;
}
need like
Patient()
{
name="Mike";
surename="Smith";
adress="New York";
ilness="Cold"
card_number=1;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int add();
int read();
string path = "base.txt";
class Patient
{
private:
char *name;
char *surename;
char *adress;
char *ilness;
int *card_number;
public:
void set()
{
cout << "Enter name:";
cin >> name;
cout << "Enter surename:";
cin >> surename;
cout << "Enter adress:";
cin >> adress;
cout << "Enter diagnosis:";
cin >> ilness;
cout << "Enter card number:";
cin >> *card_number;
}
void show()
{
cout << "Name:" << name << endl;
cout << "Surename:" << surename << endl;
cout << "Adress:" << adress << endl;
cout << "Cardnumber:" << card_number << endl;
cout << "Diagnosis:" << ilness << endl;
}
void print()
{
cout << name << surename << adress << ilness << card_number << endl;
}
Patient()
{
}
Patient(const char* s)
{
int length = 0;
while (s[length++] != ' ')
;
name = new char[length];
for (int i = 0; i < length; i++)
name[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
surename = new char[length];
for (int i = 0; i < length; i++)
surename[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
adress = new char[length];
for (int i = 0; i < length; i++)
adress[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
ilness = new char[length];
for (int i = 0; i < length; i++)
ilness[i] = s[i];
length = 0;
while (s[length++] != '\n')
;
card_number = new int[length];
for (int i = 0; i < length; i++)
card_number[i] = s[i];
}
};
int main()
{
char a;
cout << "Choose the action:" << endl;
cout << "a. Add new patient" << endl;
cout << "b. Delete patient" << endl;
cout << "c. Find for card number" << endl;
cout << "d. Find for ilnesses" << endl;
cin >> a;
switch (a)
{
case 'a':
add();
break;
case 'b':
read();
break;
default:
cout << "error" << endl;
}
system("pause");
return 0;
}
int add()
{
fstream file;
file.open(path, fstream::out | fstream::in | ofstream::app);
if (!file.is_open())
{
cout << "Error" << endl;
}
else
{
string str;
cout << "Opend" << endl;
cout << "Enter name" << endl;
cin >> str;
file << str<<" ";
cout << "Enter surename" << endl;
cin >> str;
file << str << " ";
cout << "Enter adress" << endl;
cin >> str;
file << str << " ";
cout << "Enter ilness" << endl;
cin >> str;
file << str << " ";
cout << "Enter card number" << endl;
cin >> str;
file << str<<"\n";
cout << "Sucsesfully added\n";
}
file.close();
return 0;
}
int read()
{
fstream file;
file.open(path, fstream::out | fstream::in | ofstream::app);
if (!file.is_open())
{
cout << "Error" << endl;
}
else
{
cout << "Opend" << endl;
string str;
Patient first;
while (file.read((char*)&first,sizeof(Patient)))
{
first.print();
}
}
file.close();
return 0;
}
Database example
Mike Smith New_York Cold 1
Charles Williams London Flu 2
Henry Roberts York Coronovirus 3
Robert Garcia Sydney Cold 4
methods how to write from file to class and from class to file
If you want to serialise your data structures, it's best to use a library and data format, such as JSON.
Personally, I recommend nlohmann::json because of it's ease of use and flexibility.
Overloading the constructor and serialising data
Overloading your constructor is nothing other than overloading another method in C++.
If your class is Patient:
#include <string>
#include <nlohmann/json.hpp>
using nlohmann::json;
using std::string; // Don't use using namespace std;!
class Patient {
public:
Patient() = default;
explicit Patient(const string& name, const string& surname,
const string& addr, const string& illness):
m_name(name), m_surname(surname), m_address(addr), m_illness(illness) {}
explicit Patient(const json& data) { fromJson(data); }
virtual ~Patient() = default;
json toJson() const {
return {
{ "Name", m_name },
{ "Surname", m_surname },
{ "Address", m_address },
{ "Illness", m_illness }
};
}
void fromJson(const json& data) {
if (data.contains("Name") && data["Name"].is_string()) {
m_name = data["Name"].get<string>();
} // and so on
}
void dumpJson(const string& filePath) const {
ofstream out(path, std::ios::out);
// error checking
out << filePath;
}
private: // members
string m_name;
string m_surname;
string m_address;
string m_illness;
};
I haven't tested this code and won't guarantee it will work first try, but it should point you in the right direction. This code requires at least C++11.
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.
I get an error saying: use of undeclared identifier 'again'.
I am trying to go from int main to void again and back after getting an answer.
Please explain to me why it won't work also. Thanks.
Here is my full code:
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin << answer;
string yes = "Yes";
string no = "No";
if(a == yes)
{
main();
}
}
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
}
You need to declare your fonction "again" before calling it :
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
void again();
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin >> answer;
string yes = "Yes";
string no = "No";
if(answer == yes)
{
main();
}
}
However, it's a strange things to use recursivity for what you want to do and to call main func multiple times (which is by definition, main entry of a program). In my opinion, you should call in your main function another function named like askInformation which uses a loop with a test case to know if user wants to add informations or not.
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/