C++ console crashes after running - c++

guys, i have a problem.
After i run the program, the console just crashes.
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace: __pos (which is 4294967295) > this->size() (which is 9)
I mean, you will see.In the program there is an option "Add person", and when i add one, its all okay.But when i enter the program to add second person it crashes.Please, help!
The source code of the programs is:
#include <iostream>
#include <windows.h>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;
int main(){
system("chcp 1251 > nul");
system("title PeopleData");
string firstName;
string midName;
string lastName;
string fullName;
string line;
long ID = 27560000;
int age;
char gender;
cout << "1.Add person" << endl;
cout << "2.Read file" << endl;
cout << "3.Exit" << endl << endl;
cout << "Please, enter your choice: ";
int choice;
cin >> choice;
if(choice == 1)
{
system("cls");
ofstream myfile("Data.txt", ios::app);
ifstream file("Data.txt");
string IDLine;
int numberOfLines = 0;
if (myfile.is_open())
{
while (getline (file, line) )
{
numberOfLines ++;
}
file.close();
ifstream file("Data.txt");
int y = 0;
line = "";
while(getline(file, line))
{
IDLine = line;
if(y == numberOfLines - 5)
{
goto NextStep;
}
y++;
}
}
else
{
cout << "Unable to open file";
}
NextStep:
string LastID = IDLine;
if(LastID != "")
{
LastID.replace(LastID.find("ID: "), string("ID: ").length(), "");
ID = atoi(LastID.c_str()) + 1;
}
else
{
ID = 27560000;
}
cout << "First Name: ";
cin >> firstName;
cout << endl << endl;
cout << "Middle Name: ";
cin >> midName;
cout << endl << endl;
cout << "Last Name: ";
cin >> lastName;
cout << endl << endl;
cout << "Age: ";
cin >> age;
cout << endl << endl;
cout << "Gender (m / f): ";
cin >> gender;
fullName = firstName + " " + midName + " " + lastName;
myfile << "First Name: " << firstName << "\n";
myfile << "Middle Name: " << midName << "\n";
myfile << "Last Name: " << lastName << "\n";
myfile << "Full Name: " << fullName << "\n";
myfile << "Age: " << age << "\n";
myfile << "Gender: " << gender << "\n";
myfile << "ID: " << ID << "\n";
myfile << "\n---------------\n\n";
myfile.close();
file.close();
return 0;
}
if(choice == 2)
{
system("cls");
ifstream myfile ("Data.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else
{
setcolor(12);
cout << "Unable to open file";
}
}
if(choice == 3)
{
return 0;
}
system("pause > nul");
return 0;
}
`

Related

Why can't I delete list object in C++? [closed]

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;
};

How to delete record [C++ student management system]

I'm making a student management system. All is working well, except the Delete Student Info function. I'm totally new in studying the C++ language.
When I try to use the Delete function, it will result like this, like a loop:
And this is my delete code:
void student::deleted()
{
system("cls");
fstream file, file1;
int found = 0;
string snum;
cout<<"\t\t\t\t-------------------------------------------\t\t\t"<<endl;
cout<<"\t\t\t\t---------Delete Student Information--------\t\t\t"<<endl;
file.open("Records.txt", ios::in);
if (!file)
{
cout << "\n\t\t\tNo information is available.";
file.close();
}
else
{
cout <<"\nEnter Student Number you want to remove: ";
cin >> snum;
file1.open("Records1.txt", ios::app | ios::out);
file >> student_num >> name >> bday >> address >> gender >> degree >> year;
while (!file.eof())
{
if(snum != student_num)
{
file1 << " " << student_num << " " << name << " " << bday << " " << address << " " << gender << " " << degree << " " << year ;
} else
{
found==0;
cout <<"\n\t\t\tSuccessfully Deleted.";
}
}
file1 >> student_num >> name >> bday >>address >> gender >> degree >> year ;
if (found == 0)
{
cout <<"\n\t\t\tStudent Number not found.";
}
file1.close();
file.close();
remove("Records.txt");
rename("Records.txt", "NewRecords.txt");
}
All is working on my program, except this delete function. I hope you can enlighten me with knowledge I still not know.
Basically, your whole while loop is structured wrong. Try something more like this instead:
void student::deleted()
{
system("cls");
cout<<"\t\t\t\t-------------------------------------------\t\t\t"<<endl;
cout<<"\t\t\t\t---------Delete Student Information--------\t\t\t"<<endl;
ifstream inFile("Records.txt");
if (!inFile)
{
cout << "\n\t\t\tCan't open file.";
return;
}
ofstream outFile("NewRecords.txt");
if (!outFile)
{
cout << "\n\t\t\tCan't create new file.";
return;
}
cout << "\nEnter Student Number you want to remove: ";
string snum;
cin >> snum;
bool found = false;
while (inFile >> student_num >> name >> bday >> address >> gender >> degree >> year)
{
if (snum == student_num)
{
found = true;
}
else if (!(outFile << " " << student_num << " " << name << " " << bday << " " << address << " " << gender << " " << degree << " " << year)
{
cout << "\n\t\t\tCan't write to new file.";
outFile.close();
remove("NewRecords.txt");
return;
}
}
if (!inFile.eof())
{
cout << "\n\t\t\tCan't read information.";
outFile.close();
remove("NewRecords.txt");
return;
}
outFile.close();
inFile.close();
if (!found)
{
cout <<"\n\t\t\tStudent Number not found.";
remove("NewRecords.txt");
return;
}
if (rename("Records.txt", "OldRecords.txt") != 0)
{
cout <<"\n\t\t\tCan't backup old file.";
remove("NewRecords.txt");
return;
}
if (rename("NewRecords.txt", "Records.txt") != 0)
{
cout <<"\n\t\t\tCan't rename new file.";
rename("OldRecords.txt", "Records.txt");
return;
}
remove("OldRecords.txt");
cout <<"\n\t\t\tSuccessfully Deleted.";
}

How to read from a specific line in a file (C++)

I need to find enter a number and find the specific line in my text file to correspond with the number, and I am having a little trouble, heres what I have so far:
cout << "Please enter the ID number of the student, to view their grades: ";
cin >> number;
ifstream myfile;
myfile.open("grades.txt");
if (myfile)
{
cout << " ID exam1 exam2 exam3" << endl;
cout << "---------------------------------" << endl;
getline(myfile, number);
myfile >> number >> exam1 >> exam2 >> exam3;
cout << setw(5) << number << setw(9) << exam1
<< setw(9) << exam2 << setw(9) << exam3 << endl;
cout << "---------------------------------" << endl;
total = exam1 + exam2 + exam3;
cout << "TOTAL: " << setw(25) << total << endl << endl;
}
myfile.close();
return 0;
}
Yes, you use a for loop to loop until you reach the line number, while incrementing.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
// Line #
int line;
// File
std::ifstream f("_");
// Text
std::string s;
// Prompt
std::cout << "Line #: " << std::endl;
// Store line #
std::cin >> line;
// Loop, while less than line
for (int i = 1; i <= line; i++)
std::getline(f, s);
// Output text at line
std::cout << s;
return 0;
}
This will helps : )
#include<iostream>
#include<vector>
#include<fstream>
#include<string.h>
#include<iomanip>
using namespace std;
int main()
{
int number;
cout << "Please enter the ID number of the student, to view their grades: ";
cin >> number;
ifstream myfile;
myfile.open("grades.txt");
if (myfile)
{
string string_obj;
string delimiter = " ";
int id,exam1,exam2,exam3;
size_t pos = 0;
cout << " ID exam1 exam2 exam3" << endl;
cout << "---------------------------------" << endl;
getline(myfile, string_obj);
//Split string into tokens
string token[4];
int i=0;
while ((pos = string_obj.find(delimiter)) != string::npos)
{
token[i++] = string_obj.substr(0, string_obj.find(delimiter));
string_obj.erase(0, pos + delimiter.length()); // move string for next iteration
}
token[i] = string_obj.substr(0, string_obj.find(delimiter));
id = stoi(token[0]);
if (id == number)
{
exam1 = stoi(token[1]); // convert string into int
exam2 = stoi(token[2]);
exam3 = stoi(token[3]);
}
cout << setw(5) << number << setw(9) << exam1
<< setw(9) << exam2 << setw(9) << exam3 << endl;
cout << "---------------------------------" << endl;
int total = exam1 + exam2 + exam3;
cout << "TOTAL: " << setw(25) << total << endl << endl;
}
myfile.close();
return 0;
}

How can I write C++ fstream to file?

I have a problem with this code. Could you please help me to find out why it does not save new total donation values (total) to the file (donation_total.txt)? It should be noted that the default value saved in the file is zero, but it keeps it for each iteration. I need the new value is saved at the last line each time.
Thanks
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
fstream records;
records.open("donation_total.txt", ios_base::in | ios_base::out | ios_base::app);
if (records.is_open())
{
cout << "The record file is open!" << endl;
string line;
while (!records.eof())
{
getline(records, line);
}
int total = stoi(line);
cout << "Total donation is: "<<total << endl;
cout << "Is there any new record?" << endl;
string str,newname;
stringstream field;
string name;
int donation;
getline(cin , str);
while (str=="Yes" | str=="yes")
{
cout << "Enter name and donation value: ";
getline(cin, newname);
field.str(newname);
field >> name >> donation;
total += donation;
field.clear();
cout << name << " donates " << donation << "$" << endl;
cout << "Total donation is: " << total << endl;
records << endl << total;
cout << "Is there any new record?" << endl;
getline(cin, str);
}
}
else
{
cerr << "Could not find the file!" << endl;
}
records.close();
return 0;
}
Your program has many logical incorrectness. When a name is entered with no donation amount, it takes the previously donated value.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main()
{
fstream records;
records.open("donation_total.txt", ios_base::in | ios_base::out | ios_base::app);
if (records.is_open())
{
cout << "The record file is open!" << endl;
string line;
while (getline(cin, line))
{
int total = stoi(line);
cout << "Total donation is: "<<total << endl;
cout << "Is there any new record?" << endl;
string str,newname;
stringstream field;
string name;
int donation;
getline(cin , str);
while (str=="Yes" || str=="yes")
{
cout << "Enter name and donation value: ";
getline(cin, newname);
field.str(newname);
field >> name >> donation;
total += donation;
field.clear();
cout << name << " donates " << donation << "$" << endl;
cout << "Total donation is: " << total << endl;
records << endl << total;
cout << "Is there any new record? ";
getline(cin, str);
}
break;
}
}
else
{
cerr << "Could not find the file!" << endl;
}
records.close();
return 0;
}

string read from file won't display in loop

The purpose of the following code is to take user input of 6 movie titles and realease dates, write that data to a file using fstream, then read the data into 2 string characters (line1 and line2) in a loop, such that the first loop will assign line1 and line2 the first movie title and year, and the second loop will assign line1 and 2 the 2nd movie title and year, and so on, until eof.
// array of structures
#include <iostream>
#include <string>
#include <sstream>
#include <istream>
#include <stdio.h>
#include <cctype>
#include <fstream>
#include <cassert>
#include <assert.h>
using namespace std;
#define NUM_MOVIES 6
struct movies_iit
{
string title;
int year;
}
films[NUM_MOVIES];
// global variables
char title[20], y, n;
int year;
string search;
// function 1
void sort_on_title(movies_iit films[], int n)
{
// Local struct variable used to swap records
movies_iit temp;
for (int i = 0; i < n - 1; i++)
{
for (int i = 0; i < n - 1; i++)
{
/* If s[i].title is later in alphabet than
s[i+1].title, swap the two records */
if (films[i].title > films[i + 1].title)
{
temp = films[i];
films[i] = films[i + 1];
films[i + 1] = temp;
}
}
}
}
//end function 1
//function query1 prototype
void query1(movies_iit movie);
// function query2 prototype
void query2(movies_iit movie);
// function 2 prototype
void printmovie(movies_iit movie);
int main()
{
// login
// username: user
// password: word
string mystr, pass, name, line1, line2;
int n;
char response;
// output object
ofstream fout("data.dat");
// input object
ifstream fin("data.dat");
assert(fin.is_open());
cout << "enter your username " << endl;
cin >> name;
cout << "enter your password " << endl;
cin >> pass;
cout << "\n" << endl;
if (name == "user" && pass == "word")
cout << "Welcome, user." << endl;
else
{
cout << "###" << "unrecognized username/password combination" << "\t" << "please try again" << "###" << endl;
system("PAUSE");
return 0;
}
cin.ignore(std::numeric_limits < std::streamsize > ::max(), '\n');
cout << "\n" << endl;
for (n = 0; n < NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;
}
cout << "\n" << endl;
for (int i = 0; i < NUM_MOVIES; ++i)
{
fout << films[i].title << "\n";
fout << films[i].year << "\n";
}
// sort records, function 1 call
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n = 0; n < NUM_MOVIES; n++)
printmovie(films[n]); // function 2 call
cout << "Perform an alphabetical search? (y/n)" << endl;
cin >> response;
if (response == 'y')
{
cout << "Please enter title" << endl;
cin >> title;
if (fin)
{
getline(fin, line1); // read first 2 recs
getline(fin, line2);
while (fin) // keep reading till the eof
{
if (line1 == "title")
{
cout << " >> " << line1 << endl;
cout << line2 << endl;
}
else
{
cout << line1 << endl;
cout << line2 << endl;
}
}
}
fin.close(); //close input file
response == n;
}
else if (response == 'n')
cout << "\n" << endl;
else
cout << "invalid entry" << endl;
cout << "\n" << endl;
}
// function 2 definition
void printmovie(movies_iit movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
// function query1 defintion
void query1(movies_iit movie)
{
if (movie.title == "title")
{
cout << " >> " << movie.title;
cout << " (" << movie.year << ")\n";
}
else
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
}
// function query2 definition
void query2(movies_iit movie)
{
if (movie.year >= year)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
}
In the loop where I read values from the file into my strings, in my output it does not display the data stored in the strings. Why is that, and how can I fix the issue?
I realized that the code I originally posted didn't work; here is a functional one.
You need to close the 'fout' filestream before you try to read from it using 'fin'.
fout.close(); // <== Close the output file to flush the buffered I/O
The data you are writing to the file is likely buffered (not written to the file immediately). Your data.dat file is empty when you try to read it during your search.
Close the file in which data is being stored.
You are matching for string "title" and not input which user has provided.
getline() should be inside while loop ( as you want to match all the lines and not just 1st 2 records)
int main (){
//login
//username: user
//password: word
string mystr, pass, name, line1, line2;
int n;
char response;
//output object
ofstream fout ("data.dat");
//input object
cout << "enter your username "<<endl;
cin >> name;
cout << "enter your password "<<endl;
cin >> pass;
cout << "\n" << endl;
if (name == "user" && pass == "word")
cout << "Welcome, user." << endl;
else
{cout << "###" << "unrecognized username/password combination" << "\t" << "please try again" << "###" << endl;
//system("PAUSE");
return 0;
}
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "\n" << endl;
for (n=0; n<NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline (cin,films[n].title);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> films[n].year;
}
cout << "\n" << endl;
//###################################################################################################################
//write to file
//###################################################################################################################
for (int i = 0; i < NUM_MOVIES; ++i)
{
fout << films[i].title << "\n";
fout << films[i].year << "\n";
}
fout.close();
//sort records, function 1 call
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n=0; n<NUM_MOVIES; n++)
printmovie (films[n]); //function 2 call
ifstream fin("data.dat");
assert(fin.is_open());
//###################################################################################################################
//query 1
//###################################################################################################################
cout << "Perform an alphabetical search? (y/n)" << endl;
cin >> response;
if (response == 'y')
{cout << "Please enter title" << endl;
cin >> title;
if (fin.good())
{
while(!fin.eof()) //keep reading till the eof
{
getline(fin,line1); // read first 2 recs
if(!fin.eof())
getline(fin,line2);
if (line1 == title)
{
cout << " >> " << line1 << endl;
cout << line2 << endl;
}
// else
// {
// cout << line1 << endl;
// cout << line2 << endl;
// }
}
}
fin.close(); //close input file
response == n;
}
else if (response == 'n')
cout << "\n" << endl;
else
cout << "invalid entry" << endl;
cout << "\n" << endl;
}