Program does not run again after writing code in text file - c++

I want to do a program where I key in the a question and answer to a text file with unique id(auto increment number). Currently the program only works if the text file is empty, once I have written something in the text file, the next time I run it, it does not show any output. Just blank CMD
#include<fstream>
#include<stdlib.h>
#include<string.h>
using namespace std;
class stud
{
public:
string answers, questions;
float score, totalScore;
int rollno;
stud()
{
rollno=0;
}
int get_no();
void getdata();
};
int stud::get_no()
{
ifstream outfile("questions.txt",ios::in);
int quizID;
while(!outfile.eof())
{
outfile>>rollno;
outfile>>questions;
outfile>>answers;
if(outfile.eof())
{
break;
}
}
quizID = rollno;
quizID = quizID + 1;
outfile.close();
return quizID;
}
void stud::getdata()
{
ofstream outfile("questions.txt", ios::out|ios::app);
rollno = get_no();
cout<<"Add New Question\n";
getline(cin,questions);
cout<<"Add New Answers\n";
getline(cin,answers);
outfile<<"ID "<<rollno<<": Question : "<<questions<<" Answer : "<<answers<<"\n";
outfile.close();
}
int main()
{
stud s1;
s1.getdata();
return 0;
}

Related

Reading lines from data file not returning the correct number of lines?

I made a conceptual program to add to my larger program, but I'm having an issue with a counter.
I have found plenty of excellent recourses on how to count lines in a data file (using various methods) I've tried all of them.
What is happening is, that I set up 3 arrays to hold various data. Wrote that data to a file.. and now. Before I read the data back I want to be able to know the size ( or how many lines are in the file).
I can print out all of the data from the file but the counter keeps only being set as 1.
In my larger program the number or lines will not be known to begin with.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class ReadWrite
{
public:
ofstream OutputFile,temp;
ifstream InputFile;
string taskID[3]={"1","2","3"};
string task[3]={"blah1","blah2","blah3"};
string date[3]={"11/11/1111", "12/12/1212","13/13/1313"};
string line[3];
string lines;
int count=0;
void write2file();
void readfile();
void remove();
};
void ReadWrite::readfile()
{
InputFile.open("TODOs.txt");
if (!InputFile.is_open())
{
cout<<"No saved TODOs.\n";
}
else
{
cout<<"TODOs uploading.\n";
while(InputFile>>lines);
{
cout<<lines<<endl;
count++;
}
InputFile.close();
InputFile.open("TODOs.txt");
cout<<"lines: "<<count<<endl;
for (int i=0;i<3;i++)
{
while(getline(InputFile,line[i]))
{
cout<<line[i]<<endl;
}
}
InputFile.close();
}
}
void ReadWrite::write2file()
{
OutputFile.open("TODOs.txt");
for(int i=0; i<3;i++)
{
OutputFile<<taskID[i]<<"\t"<<date[i]<<"\t"<<task[i]<<'\n';
}
OutputFile.close();
}
int main()
{
ReadWrite rw;
bool progLoop = true;
do
{
// SimpAlphaMenu sam(choices, len);
// int choice = sam.showMenu();
char choice;
cin>>choice;
if (choice=='+')
{
rw.write2file();
progLoop=true;
}
else if (choice=='-')
{cout<<"You are in -\n";}
else if (choice=='?')
{
rw.readfile();
progLoop=true;
}
else
progLoop = false;
}while(progLoop);
}
After editing in suggestions from #Retired Ninja the code seems to be working fine.
void ReadWrite::readfile() {
InputFile.open("TODOs.txt");
if (!InputFile.is_open())
{
cout<<"No saved TODOs.\n";
}
else
{
cout<<"TODOs uploading.\n";
while(getline(InputFile,lines)) //Edited this line here
{
// cout<<lines<<endl;
count++;
}
InputFile.close();
InputFile.open("TODOs.txt");
cout<<"lines: "<<count<<endl;
for (int i=0;i<3;i++)
{
while(getline(InputFile,line[i]))
{
cout<<line[i]<<endl;
}
}
InputFile.close();
} }

why is a object member variable not being updated in the file?

So i'm writing down these objects in file, reading them, and later updating stock count. I have written two objects in file and they're being read perfectly but not updating the stock after the decrement function is called. I don't want to change the data type of ID from string to character array as that won't be feasible for my project. Can it work with string?
Please help.Where's my code going wrong
#include<fstream>
#include <string>
#include <iostream>
#include<cstring>
using namespace std;
class Item
{
string ID;
char name[10];
int stock;
public:
Item()
{
}
Item(string id, char n[10], int s)
{
ID=id;
strcpy(name,n);
stock=s;
}
void writeuser(){
fstream fp;
fp.open("harmain.dat",ios::out|ios::app);
fp.write((char*)this,sizeof(Item));
fp.close();
}
void readuser(string id){
fstream fp;
fp.open("harmain.dat",ios::in|ios::out);
fp.read((char*)this,sizeof(Item));
while(1){
if(this->ID!=id){
cout<<"name:"<<name;
cout<<"stock"<<stock;
break;
}
fp.read((char*)this,sizeof(Item));
}
fp.close();
}
void decrement(string id){
fstream fp;
Item test;
fp.open("harmain.dat",ios::in|ios::out);
fstream fp2;
fp2.open("temp.dat",ios::out|ios::in);
while( fp.read((char*)&test,sizeof(Item))){
if(test.ID==id){
test.stock=test.stock-1;
fp2.write((char*)&test,sizeof(Item));
}else{
fp2.write((char*)&test,sizeof(Item));
}
}
remove("harmain.dat");
rename("temp.dat","harmain.dat");
fp.close();
fp2.close();
}
};
int main
{ Item i1;
i1.readuser("APP01");
cout<<endl;
i1.decrement("APP01");
i1.readuser("APP01");
// Item i1("APP01", "Apple",100);
// i1.writeuser();
// i1.readuser("APP01");
// Item i2("BAN01","Bananas",200);
// i2.writeuser();
}

Reading a text file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Here is what I have so far. The problem am having now is reading and inserting the strings of words I have in my text file named "word.txt" into the trie tree. I used the "void init()"function to test that the tree functions and it does but using the text file, thats where I don't know how to
any idea please
#include <iostream>
using namespace std;
#include <fstream>
#include <iomanip>
#include <string>
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
value = 0;
for (int i=0;i<26;i++){
children[i] = NULL;
}
}
int value;
TrieNode* children[26];
};
class Trie {
private:
TrieNode*root;
int count;
public:
Trie() {
root = new TrieNode();
count = 0;
}
// Inserts a word into the trie.
void insert(string s) {
TrieNode *p = root;
long int len = s.size();
for (int i=0;i<len;i++){
int index = s[i] - 'a';
if (! p->children[index]){
p->children[index] = new TrieNode();
}
p = p->children[index];
}
count++;
p->value = count;
}
// Returns if the word is in the trie.
// -1 if not in trie and not prefix of anything in trie
// 0 if not in trie but is a prefix of something in trie
// 1 if in trie
int search(string key) {
TrieNode *p = root;
long int lenght = key.size();
for (int i=0;i<lenght;i++){
int index = key[i] - 'a';
if (p->children[index]){
p = p->children[index];
}
else{
return -1;
}
}
if (p->value!=0){
return 1;
}
else{
return 0;
}
}
};
//Game class using a tree
class GhostGame{
private:
string row;
ifstream fin;
string wordSoFar = "";
string Player1,Player2;
Trie Tree;
public:
void ReadFile(){
ifstream fin("word.txt");
while (!fin.eof()) { // read file till the end
fin>>row;
getline(fin,row);
cout << row << endl;
Tree.insert(row);
}
//fin.close();
}
void init(){
Tree.insert("ab");
Tree.insert("acd");
}
//start menu
void StartGame(){
init();
cout<<"========================="<<endl;
cout<<"Welcome to Ghost Game"<<endl;
cout<<"========================="<<endl;
//ReadFile();
while(Tree.search(wordSoFar)!=1){
cout<< "Player 1 Insert a letter => ";
cin>> Player1;
cout<<setw(60)<<"now = ["<< wordSoFar <<"]"<<endl;
wordSoFar +=Player1;
if(Tree.search(wordSoFar)==1){
cout<< "Player 2 Wins "<<endl;
break;
}
cout<< "Player 2 Insert a letter => ";
cin>>Player2;
cout<<setw(60)<<"now = ["<< wordSoFar<<"]"<<endl;
wordSoFar += Player2;
if(Tree.search(wordSoFar)==1){
cout<< "Player 1 Wins "<<endl;
break;
}
}
}};
// main driver
int main()
{
GhostGame G1;
G1.StartGame();
return 0;
}
Use regular expressions for such task, they are in header file <regex>. Some good tutorials on regex can be found in book Professional C++ (Wrox) for example.
For file reading use ifstream class from <fstream>.
Open file
using fgets or get line function read the file into temporary string
check first character... Make sure to use tolower, before comparing
void findString(char *filename, char ch)
{
char temp[100];
FILE *infile = fopen(filename, "rw");
while(infile != NULL)
{
fgets(temp,100,infile);
if(tolower(temp[0]) == ch)
cout << temp;
}
fclose(infile);
}

How do I sort data from file by member of a struct? C++

Here I have a program that reads in some employee data from a file and stores them in an array of structs. What I am trying to do with the "sort_by_age" function is to sort this data based on date of birth to where the data is listed from oldest employee to youngest employee.The "read_file" function works fine, and the program compiles fine, but the output is incorrect, the program doesnt sort the data properly as i would like. Any help would be greatly appreciated.
Heres a few lines from the file to give an idea of the format
114680858 19670607 Matilda Vincent MI
114930037 19471024 Desdemona Hanover ID
115550206 19790110 Xanadu Perlman ND
116520629 19630921 Alexander Hall SD
so for example if this was all the lines in the file(its not), i want it to sort Desdemona's info first, then alexander's, then, matilda's, then xanadu's.
#include<string>
#include<iostream>
#include<fstream>
using namespace std;
struct employees // employee data
{
int ss_number;//social security
int dob;//date of birth YYYY/MM/DD Ex.) 19870314=1987/03/14
string f_name;
string l_name;
string state; //state of residence };
void read_file()//read file into array of 1000 structs
{
ifstream data("/home/www/class/een118/labs/database1.txt");
employees array[100]
if(!data.fail())
{
int i;
for(int i=0;i<100;i++)
{
data>>array[i].ss_number
>>array[i].dob
>>array[i].f_name
>>array[i].l_name
>>array[i].state;
}
for(int i=0;i<100;i++)
{
cout<<array[i].ss_number>>" "<<array[i].dob>>" "<<array[i].f_name>>" "<<
array[i].l_name>>" "<<array[i].state;
}}}
void print_person(employees e)
{
cout<<e.ss_number>>" "<<e.dob>>" "<<e.f_name>>" "<<e.l_name>>" "<<e.state;
}
void sort_by_age(employees array[])
{
employees temp;
for(int i=0;i<100;i++)
{
for(int j=i+1;j<100;j++)
{
if(array[j].dob<array[i].dob)
{
temp=array[i];
array[i]=array[j];
array[j]=temp;}
print_person(array[j]);
cout<<"\n";}}}
int main()
{
employees array[100];
read_file(array);
sort_by_age(array);
}
Use std::sort, preferably with a lambda, for example.
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
struct employee {
int social_security_id;
int date_of_birth;
string first_name;
string last_name;
string state;
};
// parses and returns a vector of employees from the given stream.
std::vector<employee> parse_employees(ifstream ifs)
{
std::string str;
std::vector<employee> v;
while (!ifs.eof()) {
employee e;
ifs >> e.social_security_id >> e.date_of_birth >> e.first_name >> e.last_name >> e.state;
v.push_back(e);
}
return v;
}
int main(int argc, char* argv[])
{
ifstream ifs("/home/www/class/een118/labs/database1.txt");
auto employees = parse_employees(ifs);
std::sort( std::begin(employees), std::end(employees),
[]( const employees &a, const employees &b )
{
return ( a.date_of_birth > b.date_of_birth );
});
for (auto e : v) {
cout << e.social_security_id << e.date_of_birth << e.first_name << e.last_name << endl;
}
}

C++ Data Corruption during reading a file

I am writing a c++ program to write data into a file in binary mode and read it from the file.
I am writing an object and reading to an object.
The problem I am facing is, when I write into the file and read it in that instance without closing the program, it works file. But after the program terminates execution, and comment out the writing code block and try to read the already written file, I get crappy output.
I am not able to understand what is going wrong.
Here is the code:
#include <fstream.h>
#include <string.h>
class Student{
protected:
char *Name, *Sub_code;
int Roll;
public:
Student(){}
};
class Details:private Student{
private:
char *Sub_Name;
int internal_marks, external_marks;
/*Methods*/
void setName();
void setRoll();
void setSubCode();
void setSubName();
void setInternalMarks();
void setExternalMarks();
public:
Details(){
Name = new char[1];
Sub_code = new char[1];
Sub_Name = new char[1];
Name[0] = '\0';
Sub_code[0] = '\0';
Sub_Name[0] = '\0';
internal_marks = 0;
external_marks = 0;
Roll = 0;
}
void setDetails();
void getDetails();
static void writeDetails(Details detail);
static void readDetails();
};
void Details::setName(){
cout<<"Enter Student Name : ";
char tmp[100];
tmp[0] = '\0';
cin>>tmp;
int len = strlen(tmp);
Name = new char[len];
strcpy(Name,tmp);
}
void Details::setRoll(){
cout<<"Enter Roll Number : ";
cin>>Roll;
}
void Details::setSubCode(){
cout<<"Enter Subject Code : ";
char tmp[100];
tmp[0] = '\0';
cin>>tmp;
int len = strlen(tmp);
Sub_code = new char[len];
strcpy(Sub_code,tmp);
}
void Details::setSubName(){
cout<<"Enter Subject Name : ";
char tmp[100];
tmp[0] = '\0';
cin>>tmp;
int len = strlen(tmp);
Sub_Name = new char[len];
strcpy(Sub_Name,tmp);
}
void Details::setInternalMarks(){
cout<<"Enter internal marks : ";
cin>>internal_marks;
}
void Details::setExternalMarks(){
cout<<"Enter external marks : ";
cin>>external_marks;
}
void Details::setDetails(){
setName();
setRoll();
setSubCode();
setSubName();
setInternalMarks();
setExternalMarks();
}
void Details::getDetails(){
cout<<Name<<"\t\t";
cout<<Roll<<"\t\t";
cout<<Sub_code<<"\t\t";
cout<<Sub_Name<<"\t";
cout<<internal_marks<<"\t";
cout<<external_marks<<"\t\n";
}
void Details::writeDetails(Details detail){
ofstream os("StudentsRecord.dat", ios::binary|ios::ate);
os.write(reinterpret_cast <char *>(&detail),sizeof(detail));
os.close();
}
void Details::readDetails(){
Details detail;
ifstream is("StudentsRecord.dat", ios::binary|ios::in|ios::beg);
cout<<"Name\tRoll\tSubject Code\tSubject Name\tInternal marks\tExternal Marks\n";
while (is.read(reinterpret_cast<char *>(&detail), sizeof(detail))){
detail.getDetails();
}
is.close();
}
int main(){
Details y,x;
/*for(int i = 0; i < 2; i++){
x.setDetails();
Details::writeDetails(x);
}*/
Details::readDetails();
return 0;
}
The commented code in the main() is the block that is used for writing the data in the file.
Here is the sample screen shot of the output I am getting.
Regards Priyabrata
The Detail class has char* inside. When you write it to the file you write the actual pointer address of the string, not the actual string. When you read it back in the same program it works because the data is still there.
When you rerun your program you get garbage because that pointer is not at some random piece of memory.
You should use a library that does serialization for you. It's kinda hard to get it right.
Take a look at https://code.google.com/p/protobuf/ , but I'm sure there are other ones as well.