Code crashes when writing text to Random Access File - c++

The data file is just an integer, a string, another integer.
For Example:
20 Bob 550
Here's the code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct RECORD
{
int ID;
string name;
float balance;
};
void Display(char fname[])
{
RECORD st;
fstream f;
f.open(fname, ios::in|ios::binary);
cout<<fixed<<showpoint<<setprecision(2);
for(int i=1; i<=5; ++i)
{
//read a record file from the RAF
f.read((char*)&st, sizeof(st));
cout<<st.ID<<'\t'<<st.name<<'\t'<<st.balance<<endl;
}
f.close();
}
int main()
{
//initalize the RAF with dummy record 0, "nnn", 0.0
fstream g;
g.open("data.raf", ios::out|ios::binary);
RECORD dummy={0, "nnn", 0.0};
for(int i=1; i<=5; ++i)
{
g.write((char*)&dummy, sizeof(RECORD));
}
g.close();
Display("data.raf");
//copy text file into RAF
fstream ftxt;
fstream fraf;
//open text file to read from
ftxt.open("data.txt", ios::in);
//open RAF to write
fraf.open("data.raf", ios::out|ios::binary);
for(int i=1; i<=5; ++i)
{
ftxt>>dummy.ID>>dummy.name>>dummy.balance;
int byteOfSet = (dummy.ID/10-1)*sizeof(RECORD);
//seekp to put (write)
//seekg to get (read)
fraf.seekp(byteOfSet, ios::beg);
//beg from beginning of file
fraf.write((char*)&dummy, sizeof(RECORD));
}
//deposit 100 in ID #40
int id;
cout<<"Enter an ID number: ";
cin>>id;
fraf.open("data.raf", ios::in|ios::out|ios::binary);
int byteOfSet = (id/10-1)*sizeof(RECORD);
fraf.seekg(byteOfSet, ios::beg);
fraf.read((char*)&dummy, sizeof(RECORD));
dummy.balance += 100;
//put the updated record back into the same place
fraf.seekp(byteOfSet, ios::beg);
fraf.write((char*)&dummy, sizeof(RECORD));
//fraf.close();
ftxt.close();
fraf.close();
Display("data.raf");
system("pause");
return 0;
}
The code runs then just dies in the console... I have no idea what's wrong. I think it might have something to do with reacessing the RAF but that's just my guess.

Related

Read from the file from different functions

I'm trying to read from the same file from another function but it doesn't work.
I guess the problem is that I'm trying to read from ifstream &input but I don't know the other way to implement that
#include <iostream>
#include <fstream>
using namespace std;
class Student{
public:
char name[40]; // i cant use string
int age;
void Input(ifstream &input)
{
input.getline(name, 40);
input >> age;
}
};
void Read(Student *students, int &numberOfStudents)
{
ifstream input("test.txt");
input >> numberOfStudents;
students = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; ++i)
students[i].Input(input);
input.close();
}
int main()
{
int size = 0;
Student *students = NULL;
Read(students, size);
for (int i = 0; i < size; ++i)
cout << students[i].name << endl << students[i].age << endl;
return 0;
}
I made my input file
3
1
2
3
4
5
6
(if the program was working correctly i should've get 1 - name age - 2 etc)
but what i got is no names with ages = 1 2 3 respectively
The program does not work because you define:
void Read(Student *students, int &numberOfStudents)
And then
int size = 0;
Student *students = NULL;
Read(students, size);
The students pointer is passed-by value so Read() can not change the memory address outside the function.
To fix this simply pass the the pointer by-reference:
void Read(Student *& students, int &numberOfStudents)
Lastly as I commented you need to account white space e.g. '\n' line ending
In the file when using >> operator to extract data:
void Input(ifstream &input)
{
input.getline(name, 40);
input >> age;
input.ignore(1);
}
Same for reading the number of students in the file.

string array omiting characters z and y

im doing an assignment for my lab which has to do with encrypting a string into a text file from another file, and it works good but my only problem is that when i encrypt or decrypt the encryption omits the letter Z and Y. I've tried changing a couple of things but nothing works, please if you know how to explain because i am lost.
this is my code so far:
#include iostream
==
#include fstream
==
#include cstring
==
#include string
==
using namespace std;
int main()
{
ifstream inputFile;
ofstream outputFile;
const int SIZE=150;
char file[SIZE];
char message[SIZE+1];
char letter;
char alphabet[]={'A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','\0'};
cout<<"Enter the message you want to encrypt: "<<endl; //getmessage
cin.getline(message,SIZE,'\n');
for(int i=0;i<strlen(message);i++){
if(islower(message[i])) //change to
message[i]=toupper(message[i]); //uppercase
}
outputFile.open("textoNoEncrypt.txt");
for(int i=0;i<strlen(message);i++){ //copy message to
outputFile.put(message[i]); //file
}
outputFile.close();
inputFile.open("textoNoEncrypt.txt");
if (inputFile.is_open()){
int i=0;
while (!(inputFile=='\0')){
inputFile>>file[i]; //reading and copying
i++; //data from file
}
}
inputFile.close();
outputFile.open("textoEncrypt.txt");
for(int i=0;i<strlen(file);i++){
int j=0;
int P=0;
int index=0;
bool found=false;
while(!found){
if(file[i]==alphabet[j]){
P=j;
index=(P+3)%26; //encrypting message
file[i]=alphabet[index];
found=true;
cout<<j<<" ";
}
j++;
}
outputFile.put(file[i]);
}
outputFile.close();
cout<<message<<endl; //show original message
cout<<file<<endl; //show encrypted message
return 0;
}
I think this is cause by the P+3 line

C++ Storing Items in Array and Setting each Token

My name is Faith and I am a beginner programmer in C++. I am working on a project where I have to read in two file and be able to separate the items in each file to its own variable. The first file has two pieces of information separated by "," and the second has three pieces of information. So far, I think I've done well with reading the files and getting each line in the file. Also I've separated each item by "," now I am trying to store those items in its on variable. Please Help! I've tried starting this project over multiple times and this is the only method I know how to implement to do this.
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
using namespace std;
class Manufactuer{
string upcode;
string company_name;
public:
void setupcode(string value){
upcode= value; }
void setcompany_name(string value){
company_name= value; }
string getupcode(){ return upcode;}
string getcompany_name(){return company_name;}
};
class Products{
string product_num;
string quantity;
string product_name;
public:
void setproduct_num(string value){
product_num= value; }
void setproduct_name(string value){
product_name= value; }
void setquantity(string value){
quantity = value;}
string getproduct_num(){ return product_num;}
string getquantity(){return quantity;}
string getproduct_name(){return product_name;}
};
int main(int argc, const char * argv[]) {
//opens the csv file
std::ifstream mccodesfile;
std::ifstream salesfile;
mccodesfile.open("mccodes.csv");
if(!mccodesfile){// file couldn't be opened
cout<<"Failed: file could not be opened"<<endl<<"Press Enter to Close:";
cin.get();
return 0;
}else
cout<<"Successfully opened file!"<<endl;
salesfile.open("sales.csv");
if(!salesfile){// file couldn't be opened
cout<<"Failed: file could not be opened"<<endl<<"Press Enter to Close:";
cin.get();
return 0;
}else
cout<<"Successfully opened file!"<<endl;
Manufactuer* upccodes;
int count; //how many elements in the array
int size; //how large the array
count = 0;
size = 2;
upccodes= (Manufactuer*)malloc(size*sizeof(Manufactuer)); //Malloc dynamatically reserve memory for variable pointer
string line;
while (getline(mccodesfile,line)) {// Taking every line from the file and putting in the variable line
Manufactuer newcode = Manufactuer(); //creating a upcode object
istringstream ss(line);
string token; //setting up split values
bool haveReadUPCode = false;
while (getline(ss,token,',')){// Separated values by comma
if(!haveReadUPCode){
newcode.setupcode(token);
haveReadUPCode = true;
}else{
newcode.setcompany_name(token);
}
}
if (count == size){
size = size * 2;
upccodes= (Manufactuer*)realloc(upccodes,size*sizeof(Manufactuer)); //Double the size while keeping the same elements
}
upccodes[count++]= newcode;
// cout<<line<<endl;
}
for (int i = 0; i<count; i++){
// cout<<upccodes[i].getcompany_name()<<endl; //Prints Manufactuers name--Works!
}
for (int i=0; i<count; i++) {
// cout<<upccodes[i].getupcode()<<endl; //Prints UPCcodes--Works
}
Products* product;
product= (Products*)malloc(size*sizeof(Products)); //Malloc dynamatically reserve memory for variable pointer
while(getline(salesfile, line)){{// Taking every line from the file and putting in the variable line
Products newProduct = Products(); //creating a product object
istringstream ss(line);
string token; //setting up split values
bool haveReadProduct = false;
while (getline(ss,token,',')){// Separated values by comma
if(!haveReadProduct){
newProduct.setproduct_num(token);
haveReadProduct = true;
} else{
newProduct.setproduct_name(token);
newProduct.setquantity(token);
}
}
if (count == size){
size = size * 2;
product= (Products*)realloc(product,size*sizeof(Products)); //Double the size while keeping the same elements
}
product[count++]= newProduct;
//cout<<line<<endl; //LINES ARE Printing!
}
}
for (int i = 0; i<count; i++){
// cout<<product[i].getproduct_name()<<endl; //Prints Product name--Works
}
for (int i = 0; i<count; i++){
//cout<<product[i].getproduct_num()<<endl; //Prints Product number--Works
}
}

input a file of words and numbers into an array c++

Okay, I am not very experienced with programming, but I have an assignment to create a c++ program that uses numerical methods to calculate the temperature of a mixture of three substances, based on the enthalpy and percent of each substance in the mixture. its basically a polynomial of h = a1*T + a2*T^2 + ... up to a6. These coefficents a1 through a6 are given in a table, for each of H20, H2, and O2. My program needs to be able to read the substance names and the values of the coefficients from a .dat file so that I can use the coefficients for my equations. That's what I need help with. How can I get the program to input the substance names and coefficient values into an array so I can use them in my equations? Sorry for the novel but I tried to give as much context as possible.
below is exactly what is in my .dat file, and what I am trying to put in an array. The substance name is first, followed by a1, a2, etc.
H2O 406598.40 440.77751 -.12006604 .000015305539 -.00000000072544769 -4475789700
H2 50815.714 9.9343506 -.000027849704 -.00000035332966 .000000000041898079 -14329128
O2 961091.64 199.15972 -.052736240 .00000897950410 -.00000000063609681 -318699310
this is my source code so far, but its not working, and I'm pretty lost.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
double myArray[21];
ifstream file("thermo2.dat");
if (file.is_open())
{
for (int i = 0; i < 21; ++i)
{
file >> myArray[i];
}
}
else
{
cout << "the file did not open";
}
for (int i = 0; i < 21; ++i)
{
cout << " " << myArray[i];
}
return 0;
}
thanks!
EDIT: started trying to work with an array of structs....I keep getting an error: no matching function for call to 'getline(std::ifstream&, double&, char)'. heres the code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct Data
{
string species;
double a1, a2, a3, a4, a5, a6;
};
int main()
{
ifstream fin;
fin.open("thermo2.dat");
if (fin.fail())
{
cout << "Failed to open file" << endl;
}
Data * database = new Data[3];
string line;
for(int i = 0; i < 3; i++)
{
getline(fin, database[i].species, '\t');
getline(fin, database[i].a1, '\t');
getline(fin, database[i].a2, '\t');
getline(fin, database[i].a3, '\t');
getline(fin, database[i].a4, '\t');
getline(fin, database[i].a5, '\t');
getline(fin, database[i].a6, '\t');
}
system("pause");
return 0;
}
Declare your structure as:
struct Data
{
string species;
double a[6];
}
And read as below:
for(int i = 0; i < 3; i++) {
fin >> database[i].species;
for (int j = 0; j < 6; j++) {
fin >> database[i].a[j];
}
}
My suggestion:
Create a struct to hold the data for each material.
struct Material
{
std::string name;
double coeffcients[6];
};
Create a function to read one Material from a stream.
std::istream& operator>>(std::istream& in, Material& mat)
{
// Read the name.
in >> mat.name;
// If there was an error, return.
// Let the calling function deal with errors.
if (!in)
{
return in;
}
// Read the coefficients.
for (int i = 0; i < 6; ++i )
{
in >> mat.coefficients[i];
if (!in)
{
return in;
}
}
return in;
};
In the main function, write the driving code.
int main()
{
// Create a vector of materials.
std::vector<Material> materials;
// Open the input file.
ifstream file("thermo2.dat");
// Read Materials the file in a loop and
// add them to the vector.
Material mat;
while (file >> mat)
{
materials.push_back(mat);
}
// Now use the vector of Materials anyway you like.
// Done with main.
return 0;
}

Ifstream is not working

#include <fstream>
#include <string>
#include <iostream>
#include "Gyvūnas.h"
#include "Maistas.h"
using namespace std;
//-------------------------------------------------------
const char CFm[] = "Maistas.txt";
const char CFg[] = "Gyvūnai.txt";
const int CMax = 100;
//-------------------------------------------------------
//--------------------------------------------------------
void Skaityti (const char CFm[], Maistas M[], int & n);
void Skaityti2 (Gyvūnas G[], int & kg);
//----------------------------------------------------------
int main(){
setlocale (LC_ALL , "Lithuanian");
Maistas M[CMax];
Gyvūnas G[CMax];
int n;
int kg;
Skaityti (CFm, M, n);
Skaityti2 (G, kg);
cout << M[1].ImtiMetus() << " " << n << endl;
system ("PAUSE");
return 0;
}
//----------------------------------------------------------
void Skaityti (const char CFm[], Maistas M[], int & n)
{
string produktas;
double kiekis;
int metai;
int mėnuo;
int diena;
ifstream fd(CFm);
fd >> n;
for (int i = 0 ; i<=n ; i++){
fd >> produktas >> kiekis >> metai >> mėnuo >> diena;
M[i].Dėti(produktas, kiekis, metai, mėnuo, diena);
}
fd.clear ();
fd.close();
}
void Skaityti2 (Gyvūnas G[], int & kg)
{
int narvas;
string pavadinimas;
int skaičius;
int produktas;
int kiekis;
int n;
ifstream fd(CFg);
fd >> n;
for (int i = 0 ; i<=kg ; i++){
fd >> narvas >> pavadinimas >> skaičius >> produktas >> kiekis;
G[i].Dėti(narvas, pavadinimas, skaičius, produktas, kiekis);
}
kg = n;
fd.close();
}
When I set breakpoints it shows that in this part ifstream cannot read variable n from file:
ifstream fd(CFm);
fd >> n;
for (int i = 0 ; i<=n ; i++){
fd >> produktas >> kiekis >> metai >> mėnuo >> diena;
M[i].Dėti(produktas, kiekis, metai, mėnuo, diena);
}
fd.clear ();
fd.close();
Errors are:
std::basic_ios
Filebuffer {_Set_eback=0xcccccccc _Set_egptr=0xcccccccc ...} std::basic_filebuf >
What you have are not errors, just values of the pointers. It seems that you can't open CFm file. Please confirm if you really have Maistas.txt in the working directory (for test, you could just move it to C:\Maistas.txt and then pass "C:\\Maistas.txt" as absolute file path.
Also, there's a way to check if the ifstream is properly opened - you can do that by checking failbit:
ifstream fd(CFm);
if(!fd.good())
{
cerr << "Could not open the file!" << endl;
return;
}
Try rename Gyvūnai.txt to Gyvunai.txt.
Using non-ascii symbols as variable-names and function-names is bad practice (Dėti,skaičius), though Visual Studio allow this, using string literals with non-ascii symbols is even worse - actual char code will depend on encoding of source file and compiler code-page settings. Compiler can treat sources as CP1251 when it's actually UTF-8 and have two chars for ū.