I'm trying to use a void function to read from a text file and allocate the size of a vector struct.
This is my void function.
void allocateFlight( ifstream &inFile, string &item,vector<Flight>&flight, int &i){
inFile.open("reservations.txt");
//check for error
if (inFile.fail())
{
cerr << "Error Opening File" << endl;
exit(1);
}
while (inFile >>item)
{
i = 0;
flight.resize(i);
if (item.size() == 3){
i++;
flight.resize(i);
}
}
}
This is kept in a separate cpp file and in my main file I declared my variables and tried calling it but I'm only getting zero when I try to compile.
string item;
int i;
fstream inFile;
//this is the flgiht array to partition the amount of flights based on the first line of text indexing
std::vector<Flight> flight;
int main(){
//pass by reference to allocateFlights
allocateFlight(inFile, item ,flight, i);
//int numFlights;
cout << flight.size();
I'm stumped trying to figure out what is wrong.
Related
I've been doing my project and the last thing I need to do is to save to and start reading a structure array from a file on startup of the program, but I can't figure out why the code isn't loading the information of the file. I know that it does save something since I can open the .dat file and read it in a text editor.
I apologize for the terrible style, but I'm still new. That's a sample of just that function in the code:
#include <iostream>
#include <string>
#include<fstream>
using namespace std;
struct property {
int num;
char nBrok[50];
char type[10];
string adress;
char outlook[20];
double price;
double size;
int nRooms;
int floor;
int status;
};
fstream fp;
void fileWrite(property bDanni[], int n) {
fp.open("dbase.dat", ios::binary | ios::out);
if (!fp) {
cout << "\n Error in file \n"; exit(1);
}
fp.write((char*)bDanni, sizeof(property) *n);
fp.close();
}
int fileRead(property bDanni[]) {
long pos; int n = 0, i; property b;
fp.open("dbase.dat", ios::binary | ios::in);
if (!fp) {
cout << "\n file does not exist\n"; return n;
}
fp.seekg(0l, ios::end);
pos = fp.tellg();
fp.close();
n = pos / (sizeof(property));
fp.open("dbase.dat", ios::binary | ios::in);
if (!fp) {
cout << "\n Error in file \n"; exit(1);
}
for (i = 0; i < n; i++) {
fp.read((char*)&b, sizeof(property));
bDanni[i] = b;
}
fp.close();
return n;
}
int main() {
property bDanni[100];
char answer;
int total = 0;
cout << "Do you wat to read from the save file?(y/n): ";
cin >> answer;
if (answer == 'y') {
int total = fileRead(bDanni);
}
}
The problem is that a C++ std::string is much more complex than a char array. The implementation is not mandated by the standard, but in common implementation, the string element contains a pointer to a character array. That means that your code only stores into the file a pointer value instead of a character string.
In C++ idiom, the std::string type is said not to be trivially copyable. And the fread-fwrite method can only be used with trivially copyable types.
That means that you will have to use serialization to replace the raw byte representation of a std::string with a sequence of bytes that represent the useful content of the object, something that you will be able to use at read time to construct back the object. Not really complex but beyond a mere fwrite.
#include<iostream>
#include<fstream>
using namespace std;
void read_file(fstream &file);
int main()
{
fstream inFile;
inFile.open("Data.txt");
if (inFile.fail())
{
cerr << "Error with opening file";
exit(1);
}
else
{
read_file(inFile);
}
inFile.close();
return 0;
}
void read_file(fstream &file)
{
int arr[100];
fstream inFile;
int number;
int number_trash;
int number_hold;
while (!inFile.eof())
{
for (int i = 0; i < 101; i++)
{
inFile >> number;
number_hold = number;
if (number != number_hold)
{
arr[i] = number;
cout << arr[i] << endl;
}
else
{
number_trash = number;
}
}
}
}
In your read_file() function, you're passing an fstream instance of an already open file, which is correct, however, later in the same function, you declare a new instance of fstream called inFile which is not open and you're trying to read from this file stream.
Remove the fstream inFile and read from the file which your function takes as an argument.
Also, your algorithm is not correct - the first if statement condition will be always evaluated to false. You're assigning number to number_hold and then you're checking for their non-equality.
As a solution, consider something like this:
void read_file(fstream &file)
{
set<int> arr; // storage for your unique numbers
while (!file.eof())
{
int number;
file >> number; // read the number
// check if this number is already in your unique list
if (arr.find(number) == arr.end()) { // If it isn't, print it out...
cout << number << endl;
arr.insert(number); // ...and put it to your unique list
}
}
}
Note that for this to work you have to include another header file called set
#include <set>
//it is a function to take file name and create it.
void createfile(string filename)
{
ofstream file;
file.open(filename,ios::out);
if(file.fail())
{
cout<<"file is failed"<<endl;
}
else
{
cout<<"file is opened"<<endl;
}
}
//it is a function which takes name of file and display it's content.
void displaycontent(string name)
{
ifstream file;
file.open(name);
string y;
while(!file.eof())
{
getline(file,y);
cout<<y<<endl;
}
}
How can I display the content of the file that I already created in the first function?
int main()
{
string filename;
cin>>filename;
createfile(filename);
displaycontent(filename);
return 0;
}
The program never writes anything to the file, so there is no content to display. Also, the loop is faulty. If an error occurs reading the file, file.eof() will never be true, the following will loop forever.
void displaycontent(string name)
{
ifstream file;
file.open(name);
string y;
while(!file.eof()) // WRONG
{
getline(file,y);
cout<<y<<endl;
}
}
Instead, you want this (omitting error-handling):
void display_file(const string &file_name) // Note pass by reference
{
std::ifstream file;
file.open(file_name);
std::string y;
while(std::getline(file,y)) {
std::cout << y << '\n';
}
}
Or better yet,
void display_file(const string &file_name)
{
std::ifstream file(file_name);
std::cout << file.rdbuf();
}
call the create function inside the display function (in else's scope )...
as the create function is passed by value so any changes that will happen to what's inside of it will stay within the scope
I'm trying to get the function getFilename to prompt the user for which file to read and then pass that to the function readFile which calculates the numbers in the file and then (using displayAverage) display the average of the numbers in the file.
I'm new to coding and can't figure out why it doesn't seem to be using the readFile function... the program prompts the user for the file but after that it just inputs a blank line. Am I calling the functions & passing the parameters correctly?
void getFilename(char fileName[])
{
cout << "Please enter the filename: ";
cin >> fileName;
return;
}
float readFile(char fileName[])
{
cout.setf(ios::fixed);
cout.precision(0);
ifstream fin(fileName);
int sum = 0;
int numValue = 0;
float grades = 0;
float average= 0;
if (fin.fail())
{
cout << "Error opening file \"" << fileName << "\"";
return false;
}
while (!fin.eof())
{
fin >> grades;
sum += grades;
numValue++;
if (numValue != 10)
cout << "Error reading file \"" << fileName << "\"";
}
fin.close();
average = sum / 10;
return average;
}
void displayAverage(int average)
{
cout << average;
return;
}
int main()
{
char* fileName;
int average;
getFilename(fileName);
readFile(fileName);
displayAverage(average);
return 0;
}
Your program has undefined behaviour since fileName does not point to anything valid that can hold data.
Unless you are required to use an array of chars to hold the filename, use std::string for fileName.
std::string fileName;
If you are required to use an array of chars to hold the filename, use
char fileName[FILENAME_LENGTH];
Make sure FILENAME_LENGTH is large enough for your needs.
I am trying to debugg this, but can't figure out the issue here. Why is it saying no matching function for a call to naiveGaussianElimination evnthough i have passed the correct parameters?
void naiveGaussianElimination(int count,float doubleCoefficient[][count+1]) {
}
int main() {
/*
Read from file and assign values to vector
*/
//File stream object
ifstream inputFile;
// store file name
string fileName;
// ask user for the file name and store it
cout << "Enter the file name:>> ";
cin >> fileName;
//Open the txt file
inputFile.open(fileName.c_str());
//search for the text file
if(!inputFile.is_open())
{
cerr << "Error opening file \n";
exit(EXIT_FAILURE);
}
else
{
cout << "File found and successfully opened. \n";
}
/*
find the number of variables in the equation
*/
int count =0;
string line;
while (getline(inputFile, line)){
count++;
}
cout << "Number of variables: " << count << endl; // show total variables in text file
// clear the eof flag and set it to top
inputFile.clear();
inputFile.seekg (0, ios::beg);
// 2D array to store augmented matrix
float doubleCoefficient [count][count+1];
naiveGaussianElimination(count,doubleCoefficient);
inputFile.close();
}
**Use dynamic array for
//2D dynamic array to store augmented matrix**
float **doubleCoefficient = new float*[count];
for (int i=0; i<(count+1); i++) {
doubleCoefficient[i] = new float[count+1];
}
}