Output stream not working without any error - c++

I would like to make program that uses bubble sorting algorithm to sort some data from input program and write sorted values into output file - however everything seems fine, but the output file is empty...
I've tried to use a console as output but it didn't help. I know that there are functions for bubble sorting, but I'm quiet new in c++ topic and would like to gain some experience in it.
#include <iostream>
#include <fstream>
#include <string>
struct Datas
{
std::string day;
float value;
};
using namespace std;
int main ()
{
fstream file_in, file_out;
string name, line, data;
Datas current [7];
cout << "Input file name with data to open" << endl;
cin>>name;
file_in.open(name.c_str());
if (file_in.fail())
{
cout << "Unable to open file - try again" << endl;
// pause(TIME);
system ("CLS"); //Clears the console
main();
} else {
cout << "Input output file name to save sort datas" << endl;
cin>>name;
file_out.open(name.c_str());
if (file_out.fail())
{
cout << "Unable to open file - try again" << endl;
} else {
while (file_in.eof() == 0)
{
for (int pointer = 0; pointer < 7; pointer++)
{
file_in >> current[pointer].day >> current[pointer].value;
}
string tmp_day;
float tmp_val;
for (int current_val = 0; current_val < 7; current_val++)
{
if (current[current_val].value > current[current_val+1].value ||
current[current_val].value > current[current_val+2].value ||
current[current_val].value > current[current_val+3].value ||
current[current_val].value > current[current_val+4].value ||
current[current_val].value > current[current_val+5].value ||
current[current_val].value > current[current_val+6].value )
{
tmp_day = current[current_val+1].day;
tmp_val = current[current_val+1].value;
current[current_val].day = tmp_day;
current[current_val].value = tmp_val;
tmp_day = current[current_val].day;
tmp_val = current[current_val].value;
}
}
for (int stream = 0; stream < 7; stream++)
{
file_out << current[stream].day << '\t' << current[stream].value << endl;
}
}
file_in.close();
file_out.close();
return 0;
system("PAUSE"); //Keeps console window open after program execution
}
}
}

Related

Getting an Xstring error in VS in a C++ login program

I am a beginner C++ programmer. I'm trying to create a program that takes logs a user into a program, Everything compiled perfectly, but when I try to run it I get an Xstring error saying this was 0x7FF6F0AACFF0".
I suppose the error could have come from the fact that I am very new to using files in code, and I needed to use them in this program as they were the only way the login and password data could be permanently saved.
I have rewritten this project over 5 times and this is the most functional variant so far. I tried using the ofstream and ifstream but I abandoned them because only one password & login was saved per file; so I think that the main error is probably contained in the Processing and Array_filler functions, all I need is a point in the right direction and I'll probably be able to resolve it.
C++:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
//bug_1 need to fix the error where the code doesn't recognize a returning user
//Project_1 need to implement a subsystem that recommends a random password & Login
//Project_2 need to implement a subsystem that requires a strong password
string Word_blip[90] = {};
string Pass_blop[90] = {};
string password;
string logWord;
string Login_1;
string Pass_1;
int KILL_SWITCH = 1;
int y = 0;
void Array_filler();
void Start_up();
void Yupper_pupper();
void processing();
void New_Login();
int main() {
Start_up();
if (KILL_SWITCH == 0) {
return EXIT_SUCCESS;
}
Yupper_pupper();
processing();
}
void Start_up() {
Array_filler();
cout << "Login:";
cin >> logWord;
cout << "Password:";
cin >> password;
for (y; y >= 90; y++) {
cout << "Preparing" << endl;
}
system("cls");
if (Word_blip[y] == logWord) {
cout << "Login accepted, welcome user:" << endl;
} else if (Word_blip[y] != logWord) {
New_Login();
}
}
void New_Login() {
string i_1_5;
cout << "Login not recognized, would you like to sign up?" << endl;
cin >> i_1_5;
if (i_1_5 == "yes") {
void Yupper_pupper();
} else if (i_1_5 == "no") {
cout << "Have a good day!" << endl;
KILL_SWITCH = 0;
} else {
cout << "That's not a valid answer ;-) please retry" << endl;
New_Login();
}
}
void Yupper_pupper() {
system("cls");
cout << "Please Sign in with your new username & Password." << endl;
cout << "New Login:";
cin >> Login_1;
cout << "New password:";
cin >> Pass_1;
void processing();
}
void processing() {
/* acts like "ofstream" or "ifstream combined; with the
ios::in and ios::out replacing the sort of "read out file"
ofstream meant with "ios::in"and the "input into file" that
ifstream provided with ios::out*/
fstream Urfile("Logins.txt", ios:: in );
string Placeholder_1;
if (Urfile.is_open()) {
getline(Urfile, Placeholder_1);
/* While Urfile = "While the file is open" Urfile = true
When the file runs out of information the file will close
making the statement false and ending the loop ;-)*/
while (Urfile) {
Placeholder_1 = Word_blip[0];
}
Urfile.close();
} else {
cout << "ERROR_OPENING_URFILE_ABORTING_PROGRAM_1" << endl;
abort();
}
fstream Myfile("Passwords.txt", ios:: in );
string Placeholder_2;
if (Myfile.is_open()) {
getline(Myfile, Placeholder_2);
while (Myfile) {
Placeholder_2 = Pass_blop[0];
}
Myfile.close();
} else {
cout << "ERROR_OPENING_MYFILE_ABORTING_PROGRAM_1" << endl;
abort();
}
Start_up();
}
void Array_filler() {
/*This function is responsible for clearing out the file
and replacing everything inside with the contents of Pass_blip and Word_blop
. Don't worry! none of the data will be lost because it was all written to the
arrays to be processed alongside the new inputs*/
fstream Urfile("Login.txt", ios::out);
if (Urfile.is_open()) {
for (int i = 0; Word_blip[i] != "\n"; i++) {
Urfile << Word_blip[i] << endl;
}
Urfile.close();
} else {
cout << "ERROR_OPENING_URFILE_ABORTING_PROGRAM_2" << endl;
abort();
}
fstream Myfile("Passwords.txt", ios::out);
if (Myfile.is_open()) {
for (int i = 0; Pass_blop[i] != "\n"; i++) {
Myfile << Pass_blop[i] << endl;
}
Myfile.close();
} else {
cout << "ERROR_OPENING_MYFILE_ABORTING_PROGRAM_2" << endl;
abort();
}
}

Error multiple definition of struct, but i dont see the error anywhere ( C++ )

made a struct, compiled my program, worked perfectly, didn't change anything, closed vm, restarted vm and vsc, and then did make in console again and it came up with this error
1 warning generated.
linking build/main.o
build/Game.o:(.bss+0x60): multiple definition of `scoreArray'
build/main.o:(.bss+0x10): first defined here
clang-5.0: error: linker command failed with exit code 1 (use -v to see
invocation)
Makefile:33: recipe for target 'build/2048' failed
make: *** [build/2048] Error 1
Here is my code, i cant see anything thats redefining it, please someone spot it for me,
here is the header file and the source file that its used in
main.cpp
/**
* File: main.cpp
* Author: not lettin u know :)
* Date: 20-11-2019
* Desc:
* Copyright: University of West of England 2017
*/
#include <stdio.h>
#include <cstdio>
#include <stdlib.h>
// include the UFCFGL301's standard library
#include <ufcfgl-30-1.h>
#include <iostream>
#include <time.h>
#include "Grid.h"
#include "Game.h"
// uncomment if you want to use the graphics library
#include <graphics.h>
using namespace std;
using namespace uwe;
/**
* main routine, implements ...
* #return success
*/
int main(void) {
srand(time(0));
Game game;
// -------Initialising Game-------
while(1){
game.chooseFunction();
grid.totalScore = 0;
grid.initGrid();
grid.addValue();
cout << "\033[2J"; // this clears the terminal
cout << "\nPlayer Score : " << grid.totalScore << "\n";
std::cout << "\nMoves = " << grid.moves << "\n\nlast input = N/A \n";
grid.setScore(grid.score);
grid.drawGrid();
// This launches graphics window where all keypresses are inputted
// this is also where we start the lambda functions in a loop
initialiseGraphics(600,400);
loop (
[&](){
},
[&](keyPress keyPress){
// w a s d are also inputted into an integer as their respective ascii value
// so this allows the use of w a s d and also the arrow keys in controlling
// the moves of the player
int kpVal = keyPress.getKeyCode();
if ( kpVal == 'q' ){
return true;
}
if ( kpVal == 'w' || kpVal == keyPress::upKey ){
cout << "\033[2J"; // this clears the terminal
grid.shiftUp();
cout << "Player Score : " << grid.totalScore << "\n";
std::cout << "\nMoves = " << grid.moves
<< "\n\nlast input = UP \n";
grid.setScore(grid.score);
grid.drawGrid();
game.checkGameState();
if(game.gameFinished == true){
return true;
}
}
if ( kpVal == 'a' || kpVal == keyPress::leftKey ){
cout << "\033[2J"; // this clears the terminal
grid.shiftLeft();
cout << "Player Score : " << grid.totalScore << "\n";
std::cout << "\nMoves = " << grid.moves
<< "\n\nlast input = LEFT \n";
grid.setScore(grid.score);
grid.drawGrid();
game.checkGameState();
if(game.gameFinished == true){
return true;
}
}
if ( kpVal == 's' || kpVal == keyPress::downKey ){
cout << "\033[2J"; // this clears the terminal
grid.shiftDown();
cout << "Player Score : " << grid.totalScore << "\n";
std::cout << "\nMoves = " << grid.moves
<< "\n\nlast input = DOWN \n";
grid.setScore(grid.score);
grid.drawGrid();
game.checkGameState();
if(game.gameFinished == true){
return true;
}
}
if ( kpVal == 'd' || kpVal == keyPress::rightKey ){
cout << "\033[2J"; // this clears the terminal
grid.shiftRight();
cout << "Player Score : " << grid.totalScore << "\n";
std::cout << "\nMoves = " << grid.moves
<< "\n\nlast input = RIGHT \n";
grid.setScore(grid.score);
grid.drawGrid();
game.checkGameState();
if(game.gameFinished == true){
return true;
}
}
return false;
}
);
}
}
Game.h
#pragma once
#include <cstdio>
#include <string>
#include <graphics.h>
#include "Grid.h"
class Game{
public:
bool canMove();
bool checkWin();
bool checkLoss();
void checkGameState();
void chooseFunction();
void printHighScores();
void writeHighScore();
bool gameFinished = false;
private:
};
extern Game game;
struct highScore {
int score;
std::string name;
};
Game.cpp
#include "Grid.h"
#include "Game.h"
#include <sstream>
#include <unistd.h>
#include <iostream>
#include <cstdio>
#include <graphics.h>
#include <fstream>
#include <string>
#include <algorithm> //std::sort for array of structs sorting based on struct
// integer
Grid grid;
highScore scoreArray[100];
// functions to check game state for win or loss or can make moves
bool Game::canMove(){
bool canMove = false;
for(int x = 0; x < Grid::tilesWide; x++){
for(int y = 0; y < Grid::tilesHigh; y++){
if (grid.grid[x][y] == Grid::emptyCell) {
canMove = true;
return canMove;
}
// multiple if statements due to if grid[3][1] was being checked with
// grid[3+1][1] then it would loop around and check against grid[1][2]
// for an unknown reason, so to combat this i had to check specifically against
// the edge of the board
else if(y == 3 && x < 3){
if( grid.grid[x][y] == grid.grid[x+1][y] ){
canMove = true;
return canMove;
}
}
else if(x == 3 && y < 3){
if( grid.grid[x][y] == grid.grid[x][y+1] ){
canMove = true;
return canMove;
}
}
else if( ( x < 3 && y < 3 ) &&
(grid.grid[x][y] == grid.grid[x][y+1] ||
grid.grid[x][y] == grid.grid[x+1][y]) ) {
canMove = true;
return canMove;
}
}
}
return canMove;
}
bool Game::checkWin(){
bool win = false;
for(int x = 0; x < Grid::tilesWide; x++){
for(int y = 0; y < Grid::tilesHigh; y++){
if(grid.grid[x][y] == 2048){
win = true;
return win;
}
}
}
return win;
}
bool Game::checkLoss(){
bool loss = false;
if(canMove() == false ){
loss = true;
return loss;
}
return loss;
}
void Game::checkGameState(){
if(checkWin() == true) {
std::cout << "\n\n--------YOU WIN--------\n\n";
gameFinished = true;
writeHighScore();
}
else if(checkLoss() == true) {
std::cout << "\n\n--------YOU LOSE--------\n\n";
gameFinished = true;
}
}
// functions for initializing game/options
void Game::chooseFunction(){
while(1){
int function = 0;
std::cout << "\nPlease Choose A Function\n1) Play Game\n2) High Scores"
<< "\n3) Exit Program";
std::cout << "\nFunction : ";
std::cin >> function;
if (std::cin.fail() || function < 1 || function > 3) {
std::cin.clear();
std::cin.ignore(1000,'\n'); // this is to stop the validation from
// looping for each wrong character entered
std::cout << "Not a valid option, Please re-enter \n\n" ;
sleep(1);
}
else if (function == 1) {
std::cout << "------Launching Game------\n\n";
std::cout << "---------LOADING---------\n";
for(int x=0;x < 5;x++){
std::cout << "|||||" << std::flush;
sleep(1);
}
return ;
}
else if (function == 2) {
std::cout << "---Printing High Scores---\n";
std::cout << "---------LOADING---------\n";
for(int x=0;x < 5;x++){
std::cout << "|||||" << std::flush;
sleep(1);
}
printHighScores();
sleep(10);
}
else if (function == 3) {
std::cout << "-------Now Exiting------- \n\n" << std::flush ;
std::cout << "---------LOADING---------\n";
for(int x=0;x < 5;x++){
std::cout << "|||||" << std::flush;
sleep(1);
}
exit(0);
}
}
}
// This function is called upon a win, and writes the high score ,of those who
// win the game, into a text file under the format of SCORE - NAME
void Game::writeHighScore(){
std::string name;
std::cout << "\nEnter Name To Store High Score ( Max 16 Characters )\n"
<< "Name : ";
std::getline(std::cin,name);
// this is to stop the string being over 16 characters
if(std::cin.fail() || name.length() > 16){
std::cout << "\n\nPlease Enter A Max of 16 Characters\n\n";
writeHighScore();
return;
}
else{
// This opens the output stream to the high scores text file
// and immediately points to the next free line in the file
std::ofstream HighScore;
HighScore.open ("HighScores.txt", std::ios::app);
HighScore << grid.totalScore << " "<< name << std::endl;
HighScore.close();
return;
}
}
// simple comparator function to be used with std::sort in order to sort
// the array of structs containing scores and their respective player names
bool sortScore(highScore a,highScore b){
return a.score > b.score;
}
// this function prints the high scores from the text file, however
// im not sure how to sort a text file each time its appended, so instead
// when this function is called, it seperates the lines of the files into
// the score and their respective player name, these are stored in a struct
// object for each line, and then the array of structs is sorted using
// std::sort and the comparator function and then the first 10 scores and names
// in the struct array are printed, TLDR, prints Top 10 scores :)
//
// not on the spec for the assignment but i enjoyed learning about how
// i would go about making something like this :)
void Game::printHighScores() { // function to choose and print ascii art
std::ifstream highScores;
highScores.open("HighScores.txt");
std::string line;
int i=0;
if(!highScores){
std::cout << "\nCould Not Open HighScores.txt";
sleep(2);
return;
}
else{
while(getline(highScores, line)){
std::istringstream iss(line);
int score;
std::string name;
// this seperates out the score and the name string from each line in the file
if(!(iss >> score && iss.ignore() && std::getline(iss,name))){
break;
}
// this adds to the array of structs defined in the header file
scoreArray[i].score = score;
scoreArray[i].name = name;
i++;
}
std::sort(&scoreArray[0],&scoreArray[100],sortScore);
}
// and finally... this prints the top 10 scores
std::cout << "\n\n-------HIGH SCORES-------\n\n";
for(int i=0; i<10; i++){
std::cout <<i+1<<") "<<scoreArray[i].score<<" - "<<scoreArray[i].name
<<"\n";
}
}
The line
highScore scoreArray[100];
in your header declares a variable whenever this header is included. I assume that header is included by multiple source files.
Move this into a .cpp and add an extern for it to the header.
Basically, for each source file that includes this header, you're declaring a variable called scoreArray. Each .cpp that includes this header will declare its own scoreArray. The linker, when doing its linking thing, will encounter two variables with the same name and can't decide which one is "correct," so it gives up and generates the error that you're seeing.
So, you need to move the definition into a .cpp and just reference it as an extern in the header. (There are a few different approaches to this. Choose whichever suits you best.)

how to use strstr()?

i want to take data from file and store it in string array and and perform a search function with only few information like type"j" and the program able to look for data name which contain "j".
but my program cannot work.....
i am wondering am i using the strstr() correctly or not?
my text file :
Jason Derulo
5000
Martin Delux
8752
Justin Haber
51855
Alex Zander
52163
and
coding:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
//---------------------------------------------------------------------------------------------------------
typedef struct
{
char name[30],adv_srh_name[30];
double balance;
}ACCOUNT;
int main()
{
ACCOUNT record[31];
int choice,acc_amount=0;
ifstream openfile("list.txt"); //open text file
if (!openfile)
{
cout << "Error opening input file\n";
return 0;
}
else
{
ACCOUNT temp;
int i = 0;
double d = 0;
while (openfile)
{
openfile.getline(temp.name, 30, '\n');
//consume the newline still in the stream:
if ((openfile >> d).get()) { temp.balance = d; }
record[i] = temp;
i++;
}
openfile.close(); //close text file
acc_amount = i;
}
cout << "Please enter a client name:";
fflush(stdin);
cin.getline(adv_srh_name, 30);
for (int j = 0; adv_srh_name[j] != NULL; j++)
adv_srh_name[j] = toupper(adv_srh_name[j]);
cout << adv_srh_name;
for (int a = 0; a < acc_amount; a++)
{
if ((strstr(record[a].name, adv_srh_name)) != NULL)
{
cout << "Name :" << record[a].name << "\n";
cout << "Balance :" << record[a].balance << "\n\n";
}
}
return 0;
}

C++ Simple Multicolumn File Read

I am trying to read a file with multiple columns to output all results with an income of over $100,000 and a GPA of less than or equal to 2.3. I'm not able to figure out which approach is correct. The file output does not even appear on the terminal. Please let me know if more specifics are needed. Here is the FILE.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
char *student = new char[];
int salary=100000,
grades=2.3;
inputFile.open("Students.txt");
if(inputFile.fail()==1)
{
cout<<"File opening failed";
}
else
{
while(!inputFile.eof())
{
inputFile>>student;
}
inputFile.close();
}
int income=student[0];
int gpa=student[0];
for(int i=0;i!=inputFile.eof();i++)
{
income=student[i];
gpa=student[i];
if(income>=salary && gpa<=grades)
{
cout<<" "<<income<<" "<<gpa<<endl;
}
}
cin.get();
cin.get();
return 0;
}
#include <fstream>
#include <iostream>
const int MAX_STUDENTS = 100;
int main()
{
int numberOfStudents = 0;
//Instantiate read file object
std::ifstream inputFile("Student.txt");
//Instantiate an array of income
int income[MAX_STUDENTS];
float gpa[MAX_STUDENTS];
//Check if the file is open
if(inputFile.fail() == 1)
std::cout << "\nFile opening failed!\n";
else
{
while(!inputFile.eof())
{
//Read file into class
inputFile >> income[numberOfStudents];
inputFile >> gpa[numberOfStudents];
//^^**In whatever order your data members are in**
//Check if gpa and income meet requirements
if(income[numberOfStudents] > 100000 && gpa[numberOfStudents] <= 2.3)
{
/*Output student if gpa is less than or equal to 2.3 AND
greater than 100000*/
std::cout << "\nStudent #: " << numberOfStudents + 1 << ' ' << std::endl;
std::cout << income[numberOfStudents] << ' ';
std::cout << gpa[numberOfStudents] << ' ';
std::cout << ' ' << std::endl;
}
//Increase number of students
numberOfStudents++;
}
//Close file
inputFile.close();
}
return 0;
}

C++. After writing into a relative file, I cannot display the content

I can write into a relative file1, then when I try to read the content and display it on the screen (to check if data are actually into the file), I do not have the records which I believe are already present in the file. I am using Dev-C++. Any help will be appreciated. The code is below;
#include <iostream> // cin, cout
#include <iomanip>
#include <fstream>
#include <conio.h>
using namespace std;
#define SIZE 10
struct client // Client record
{
int account; // from 1 to SIZE
char name[20];
double balance;
};
void make_file(char filename[], int number_of_records)
{
cout << "\nMAKE_FILE: Creating a blank relative file " << filename
<< " containing " << number_of_records << " records.";
ofstream OS(filename, ios::out);
if(!OS) {cerr << "File open error." << endl; exit(1);}
client blank={0, "", 0.0}; // Create an empty client record
while(number_of_records--)
OS.write((char *)&blank, sizeof(blank));
cout << "\nFile created.";
OS.close();
}
int main(void)
{
client c;
void *ptr;
int n=0;
char *fname = "credit.txt";
make_file(fname, SIZE);
fstream iof("credit.txt",ios::in | ios::out);
if(!iof)
{
cerr<<"File open error! "<<endl;
exit(1);
}
cout<<"\n\nenter the 10 customers into the file: "<< fname<<endl<<endl;
while(0 < c.account) // && c.account <= maxrec)
{
iof.seekp((c.account-1) * sizeof(client)); // position the pointer
iof.write((char *)&c, sizeof(c));
cout << "Account[1.."<< SIZE
<< "], Name, Balance (0 0 0 to exit)= ";
cin >> c.account >> c.name >> c.balance;
}
cout << "\n\nSHOW_FILE: The contents of file " << fname;
iof.seekg (0, ios::beg);
while(iof.read((char *)&c, sizeof(c))) //where I think the problem is
{
cout <<'\n'<< setw(3)<< ++n << setw(6) << c.account <<setw(20)
<< c.name << setw(10) << c.balance ;
// << " | " << IS.eof() << " " << ptr;
}
iof.close();
cout << "\n\n";
system("pause");
return 0;
}
A relative file is a file in which each record is identified by its ordinal position in the file allowing for random as well as sequential access.
Relative Files
Relative file organization
http://cayfer.bilkent.edu.tr/~cayfer/ctp108/relative.htm
You need to use binary reading/writing.
fstream iof("credit.txt",ios::in | ios::out | ios::binary);
In your code, in first loop, c.account is not initialitzed. Perhaps you are overwriting file with uninitialized values:
while(0 < c.account) // <--- c.account is not initialized!!
{
iof.seekp((c.account-1) * sizeof(client)); // position the pointer
iof.write((char *)&c, sizeof(c)); // <-- overwriting data??
You're program intrigued me since I haven't done too much work with iostream. If you were ever working with data that had to be edited on a per record basis you'd use some type of database or specialized library that would encapsulate you from all this stuff, such as an xml library. Since your data is so small it's easier to just load all of it into your application using an array of your data structs. After, when you've got new user input, it's easiest clear the file, and the write the data fresh. Here is what I did.
#include <stdio.h>
#include <tchar.h>
#include <iostream> // cin, cout
#include <iomanip>
#include <fstream>
#include <conio.h>
using namespace std;
#define SIZE 10
#define BUFFER_SIZE 100
#define NAME_SIZE 20
struct client // Client record
{
int account; // from 1 to SIZE
char name[NAME_SIZE];
double balance;
};
/* Makes file if files does not exist.
* Returns true if file already exists
*/
bool make_file(char filename[], int number_of_records)
{
// Check if file exists
fstream file;
file.open(filename, ios_base::out | ios_base::in); // will not create file
if (file.is_open())
{
file.close();
return true;
}
else
{
file.clear();
file.open(filename, ios_base::out);
if(!file) {cerr << "File open error." << endl; exit(1);}
cout << "File created. \n";
file.close();
return false;
}
}
/* Create an application that reads x number of accounts from a text file
* into an array of client data structures.
*/
int _tmain(int argc, _TCHAR* argv[])
{
client clientArray[SIZE];
char cleanName[NAME_SIZE];
for(int i = 0; i < NAME_SIZE; i++)
cleanName[i] = NULL;
// Make file if doesn't not exist.
char *fname = "credit.txt";
bool fileExisted = false;
fileExisted = make_file(fname, SIZE);
// initialize client array
for(int j = 0; j < SIZE; j++)
{
clientArray[j].account = -1;
strcpy_s(clientArray[j].name, cleanName);
clientArray[j].balance = 0.0;
}
// Open file and populate the client array
fstream readFile("credit.txt", ios::in | ios::binary);
if(fileExisted)
{
if(!readFile)
{
cerr<<"File open error! "<<endl;
exit(1);
}
int index = 0;
bool firstRun = true;
client temp;
while(index < SIZE)
{
readFile >> temp.account;
readFile >> temp.name;
readFile >> temp.balance;
if(readFile.eof())
break;
if(firstRun)
{
cout << "Data read \n";
cout << "----------\n";
firstRun = false;
}
clientArray[index].account = temp.account;
strcpy_s(clientArray[index].name, temp.name);
clientArray[index].balance = temp.balance;
cout << setw(3) << index+1;
cout << setw(6) << clientArray[index].account;
cout << setw(20) << clientArray[index].name;
cout << setw(10) << clientArray[index].balance << "\n";
index++;
}
readFile.close();
readFile.clear();
}
// Get user input
{
client temp; // Create and initialize temp client
temp.account = 0;
temp.balance = 0;
strcpy_s(temp.name, cleanName);
int index = 0;
bool keepLooping = true;
while(keepLooping)
{
cout << "Account[1.."<< SIZE << "], Name, Balance (-1 to exit)= ";
cin >> temp.account;
// If user exited
if(temp.account == -1)
keepLooping = false;
else
{
cin >> temp.name; // If not keep reading data
cin >> temp.balance;
// Find either unused account or same account
bool found = false;
int firstEmpty = -1;
for(int i = 0; i<SIZE; i++)
{
if(temp.account == clientArray[i].account) // Same account found
{
strcpy_s(clientArray[i].name, temp.name);
clientArray[i].balance = temp.balance;
found = true;
break;
}
else if((clientArray[i].account == -1)&&(firstEmpty == -1)) // Empty account found
{
firstEmpty = i;
}
}
if((firstEmpty != -1)&&(!found)) // Copy input to empty account
{
clientArray[firstEmpty].account = temp.account;
strcpy_s(clientArray[firstEmpty].name, temp.name);
clientArray[firstEmpty].balance = temp.balance;
}
else if(found) //
{
cout << "Updating Client Data. \n";
}
else // No empty accounts break loop
{
cout << "Client array is full!\n";
keepLooping = false;
}
}
}
} // end of user input scope
// Clear file and write only valid data to new file
{
ofstream out;
out.open("credit.txt");
for(int i=0 ; i<SIZE ; i++)
{
if(clientArray[i].account != -1)
{
out << clientArray[i].account << "\t";
out << clientArray[i].name << "\t";
out << clientArray[i].balance << "\n";
}
}
out.close();
out.clear();
}
// Open file and read the data
{
ifstream readFile("credit.txt", ios::in | ios::binary);
// readFile("credit.txt", ios::in | ios::binary);
if(!readFile)
{
cerr<<"File open error! "<<endl;
exit(1);
}
if(!readFile.good())
{
cerr<<"File open error!2"<<endl;
exit(1);
}
int index = 0; // scope variables
client temp;
temp.account = 0;
temp.balance = 0;
strcpy_s(temp.name, cleanName);
cout << "\nAccounts" << "\n";
cout << "----------" << "\n";
bool readFileb = readFile.good();
while(index < SIZE)
{
readFile >> temp.account;
readFile >> temp.name;
readFile >> temp.balance;
if(readFile.eof())
break;
cout << setw(3) << index+1;
cout << setw(6) << temp.account;
cout << setw(20) << temp.name;
cout << setw(10) << temp.balance << "\n";
index++;
}
readFile.close();
readFile.clear();
}
system("pause");
}