I am having an issue with my function in c++ that saves a structure to a file. It appears to save everything correctly, when I open the file back up everything has been saved. But when I run the program again the loading file goes into an infinite loop for some reason, I am uncertain as to why this is happening. Any input would be welcome.
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>
using namespace std;
struct account
{
string acctNum;
string name;
float cBal;
float sBal;
};
int menu();
char subMenu();
int loadCustomers(account[]);
void saveCusomers(account[], int);
int newCustomer(account[], int);
int deleteCustomer(account[], int);
int findCustomer(account[], int);
void deposit(account[], int);
void withdrawl(account[], int);
void balance(account[], int);
void bankBalance(account[], int);
int main()
{
account acc[20];
int selection;
int numAcc = 0;
numAcc = loadCustomers(acc);
saveCusomers(acc, numAcc);
return 0;
}
int loadCustomers(account acc[])
{
ifstream inFile;
int numCustomers = 0, i = 0;
inFile.open("customer.dat");
if (!inFile)
{
cout << "No customer file found." << endl;
}
else
{
cout << "Customer file found..." << endl << endl;
while (!inFile.eof())
{
getline(inFile, acc[i].acctNum, '#');
getline(inFile, acc[i].name, '#');
inFile >> acc[i].cBal;
inFile.ignore();
inFile >> acc[i].sBal;
i++;
numCustomers++;
}
cout << "Number of customers found in file: " << numCustomers << endl;
}
inFile.close();
return numCustomers;
}
void saveCusomers(account acc[], int numCustomers)
{
ofstream outFile;
outFile.open("customer.dat");
for (int i = 0; i < numCustomers; i++)
{
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}
outFile.close();
}
I am not sure if I am saving it infinitely or why it loops infinitely, any comments would help.
try replacing
while (!inFile.eof())
with
while(getline(inFile, acc[i].acctNum, '#'))
and remove
getline(inFile, acc[i].acctNum, '#');
as first statement in you while
Related
So I made a function that reads lines from two files and writes them to a vector. Called the function twice, once for each of the files. Now how should I go for writing the content of the vector to a new file? Also, am I doing it correctly?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
bool getFile(string filename, vector<string> & vecOfStrs){
ifstream in(filename.c_str());
if (in.fail()) {
cout << "No such file" << "\n";
return 1;
}
string str;
while (getline(in, str))
{
if (str.size() > 0)
vecOfStrs.push_back(str);
}
in.close();
return true;
}
int main(){
vector<string> A;
string lecCourse;
cout << "First file: ";
cin >> lecCourse;
string lab_ex;
cout << "Second file: ";
cin >> lab_ex;
string exit;
cout << "Name of exit file: " << "\n";
cin >> exit;
bool result = getFile(lecCourse, A);
bool result2 = getFile(lab_ex, A);
ofstream output;
output.open(exit.c_str());
if (output.fail()) {
cout << "error" << "\n";
return 1;
}
}
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
vector<string> A;
bool getFile(string filename, vector<string> & vecOfStrs){
ifstream in(filename.c_str());
if (in.fail()) {
cout << "No such file" << "\n";
return 1;
}
string str;
while (getline(in, str))
{
if (str.size() > 0)
vecOfStrs.push_back(str);
}
in.close();
return true;
}
int main()
{
string lecCourse;
cout << "First file: ";
cin >> lecCourse;
string lab_ex;
cout << "Second file: ";
cin >> lab_ex;
string exit;
cout << "Name of exit file: " << "\n";
cin >> exit;
bool result = getFile(lecCourse, A);
bool result2 = getFile(lab_ex, A);
ofstream output;
output.open(exit.c_str());
for(int i=0;i<A.size();i++)
{
output<<A[i]<<"\n";
}
if (output.fail()) {
cout << "error" << "\n";
return 1;
}
}
Hope!!
This might helps:))
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
void wordCount(ifstream& in_stream, ofstream& out_stream);
int main()
{
char inputFile[100];
ifstream fin;
ofstream fout;
cout << "Enter a File name: " << endl;
cin >> inputFile;
fin.open(inputFile);
if (fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
wordCount(fin, fout);
fin.close();
fout.close();
return 0;
}
void wordCount(ifstream& in_stream, ofstream& out_stream)
{
int counter = 0,i;
char next,last[1];
in_stream.get(next);
while (!in_stream.eof())
{
if (next == ' ')
(next >> last[1]);
for(i = 0; last[i] != '\0'; ++i)
{
if (last[i] == ' ')
counter++;
}
in_stream.get(next);
}
}
I'm trying to get the word count of this and its not working
the chars being saved are fine, but whats not working if I input from notepad a file with something like:
I
am
working
it will show 0 words if I I type normally it will count the words why is that?
I edit your code, Do you mean something like this?
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int wordCount(ifstream& in_stream, ofstream& out_stream);
int main()
{
char inputFile[100];
ifstream fin;
ofstream fout;
cout << "Enter a File name: " << endl;
cin >> inputFile;
fin.open(inputFile);
if (fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
int WordCount = wordCount(fin, fout);
fin.close();
fout.close();
return 0;
}
int wordCount(ifstream& in_stream, ofstream& out_stream)
{
int counter = 0;
char data[100];
in_stream >> data;
while (strlen(data)>0)
{
counter++;
in_stream >> data;
}
return counter;
}
I want to extract data from a file and store them into the myWorld but my for loop doesn't work, the program doesn't loop one time once it gets to the for loop. I'm not sure what the problem is. This is my code so far.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
struct Country
{
double pop1950;
double pop1970;
double pop1990;
double pop2010;
double pop2015;
string name;
};
const int MAXCOUNTRIES = 300;
struct World
{
int numCountries;
Country countries[MAXCOUNTRIES];
} myWorld;
void printPop ();
int main ()
{
printPop();
return 0;
}
void printPop()
{
ifstream inFile("population.csv");
if (!inFile.fail())
{
cout << "File has opened successfully.";
}
if (inFile.fail())
{
cout << "File has failed to open.";
exit(1);
}
for (int i = 0; i < MAXCOUNTRIES; i++)
{
inFile >> myWorld.countries[i].pop1950 >> myWorld.countries[i].pop1970 >> myWorld.countries[i].pop1990
>> myWorld.countries[i].pop2010 >> myWorld.countries[i].pop2015;
getline (cin, myWorld.countries[i].name);
cout << "loop is running" << endl;
}
inFile.close();
}
I think your loop is running, its just waiting for user input here :
getline (cin, myWorld.countries[i].name);
my text file was like
Jason Derulo
91 Western Road,xxxx,xxxx
1000
david beckham
91 Western Road,xxxx,xxxx
1000
i'm trying to get the data from a text file and save it into arrays however when i want to store the data from the text file into array it loop non-stop. what should i do ? the problem exiting in looping or the method i get the data from text file ?
code:
#include <iostream>
#include <fstream>
using namespace std;
typedef struct {
char name[30];
char address[50];
double balance;
} ACCOUNT;
//function prototype
void menu();
void read_data(ACCOUNT record[]);
int main() {
ACCOUNT record[31]; //Define array 'record' which have maximum size of 30
read_data(record);
}
//--------------------------------------------------------------------
void read_data(ACCOUNT record[]) {
ifstream openfile("list.txt"); //open text file
if (!openfile) {
cout << "Error opening input file\n";
return 0;
} else {
int loop = -1; //size of array
cout << "--------------Data From File--------------"<<endl;
while (!openfile.eof()) {
if (openfile.peek() == '\n')
openfile.ignore(256, '\n');
openfile.getline(record[loop].name, 30);
openfile.getline(record[loop].address, 50);
openfile >> record[loop].balance;
}
openfile.close(); //close text file
for (int i = 0; i <= loop + 1; i++) {
cout << "Account " << endl;
cout << "Name : " << record[i].name << endl;
cout << "Address : " << record[i].address << endl;
cout << "Balance : " << record[i].balance << endl;
}
}
}
Use ifstream::getline() instead of ifstream::eof() in tandem with >>. The following is an illustrative example, (and for simplicity I didn't check to see if the stream opened correctly).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define ARR_SIZE 31
typedef struct {
char name[30];
char address[50];
double balance;
} ACCOUNT;
int main() {
ACCOUNT temp, record[ARR_SIZE];
ifstream ifile("list.txt");
int i=0;
double d=0;
while(i < ARR_SIZE) {
ifile.getline(temp.name, 30, '\n');//use the size of the array
ifile.getline(temp.address, 50, '\n');//same here
//consume the newline still in the stream:
if((ifile >> d).get()) { temp.balance = d; }
record[i] = temp;
i++;
}
for (int i=0; i < ARR_SIZE; i++) {
cout << record[i].name << "\n"
<< record[i].address << "\n"
<< record[i].balance << "\n\n";
}
return 0;
}
Another recommendation would be to use vectors for record array, and strings instead of char arrays.
REFERENCES:
Why does std::getline() skip input after a formatted extraction?
Main.cpp
#include <iostream>
#include <fstream>
#include "steganography.h" // call steganography class
const int arrSize = 30000;//array for contains pixels
using namespace std;
int main()
{
char FileName[20] = "new.txt";
char NewFile[20] = "new.ppm";
char arrPixel[arrSize] = {};
int count = 0;
int option;
Steganography A;//create the reference of steganopragpy class
cout<<"Choose Enocde/Decode[1/2]"; // take option from user
cin>>option;
switch(option)
{
case 1:
cout << "Enter PPM File Name" << endl;
cin>>FileName;
cout << "Enter Output File Name"<< endl;
cin>>NewFile;
A.readImage(FileName, arrPixel);//call readImage method
cout << "Encoded Successfully completed:" << endl;
A.printImage( NewFile, arrPixel);//write ppm
break;
case 2:
cout << "Enter Input File Name" << endl;
cin>>FileName;
cout << "Enter Output PPM File Name"<< endl;
cin>>NewFile;
A.readCipherText( NewFile, arrPixel);//call read file method
cout << "Decoded Successfully completed:" << endl;
A.printCipherText(FileName, arrPixel);//write ppm
break;
default:
cout<<"wrong choice";
}
// cout << NewFile << endl;
for(int ct = 0; ct > arrSize; ct++)
{
cout << arrPixel[ct];
}
return 0;
}
steganography.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "steganography.h" // call steganography class
const int arrSize = 30000;//array for contains pixels
using namespace std;
Steganography::Steganography()//call steganography constructor
{
char arrPixel[arrSize] = {};
}
void Steganography::readImage(char* FileName, char* arrPixel)//read image
{
ifstream infile (FileName);//open file
if(infile.is_open())
{
for(int count = 0; count < arrSize; count++)
{
infile >> noskipws >> arrPixel[count];
}
}
else
{
cout << "Error opening new file." << endl;
//abort();
}
infile.close();
}
void Steganography::readCipherText(char* FileName, char* arrPixel)//read text file contains ppm info
{
ifstream infile (FileName);
if(infile.is_open())
{
for(int count = 0; count < arrSize; count++)
{
infile >> noskipws >> arrPixel[count];
}
}
else
{
cout << "Error opening new file." << endl;
//abort();
}
infile.close();
}
void Steganography::printImage(char* NewFile, char* arrPixel)//write image
{
ofstream outfile (NewFile);
if(outfile.is_open())
{
int count = arrSize;
for(int i = 0; i < (count - 1); i++)
{
outfile << arrPixel[i];
}
}
else
{
cout << "Error opening new file." << endl;
// abort();
}
outfile.close();
}
void Steganography::printCipherText(char* NewFile, char* arrPixel)//write ppm file
{
ofstream outfile (NewFile);
if(outfile.is_open())
{
int count = arrSize;
for(int i = 0; i < (count - 1); i++)
{
outfile << arrPixel[i];
}
}
else
{
cout << "Error opening new file." << endl;
// abort();
}
outfile.close();
}
steganography.h
#ifndef STEGANOGRAPHY_H
#define STEGANOGRAPHY_H
#include <string>
#include <vector>
class Steganography {
private:
// Image header
std::string image_type;
int width, height;
int max_color_depth;
// Image data
std::vector<int> color_data;
// Hidden data
std::string ciphertext;
int getNthBit(char cipher_char, int n);
public:
Steganography(void); //Constructor
void readImage(char*,char*);
void printImage(char*,char*);
void readCipherText(char*,char*);
void printCipherText(char*,char*);
void cleanImage();
void encipher();
void decipher();
};
#endif
When I compile, i get this warning:
steganography.cpp: In constructor ‘Steganography::Steganography()’:
steganography.cpp:11:10: warning: unused variable ‘arrPixel’ [-Wunused-variable]
Can someone help me figuring out the problem. Also,I have to write this line const int arrSize = 30000; in both Main.cpp and steganography.cpp to avoid getting errors, is there a way to write it only on steganography.cpp without getting errors?
Here:
Steganography::Steganography()//call steganography constructor
{
char arrPixel[arrSize] = {};
}
You declare a local variable called arrPixel and you don't use it. You can remove that line.
Note that you have a warning, not an error.