I am working with a dynamic declaration of a 3 dimensional array of type CString. (I know, why CString again? Use vectors! I can't, the assignment requires use of cstring.)
So the assignment is to make a user defined playlist of songs which allows adding, removing, displaying, and searching. Also, the playlist must save to a text file called songs.txt.
My problem is I keep getting memory leaks in my adding function I will share all code and memory leak errors, so you can see.
Valgrind Errors:
==17401== HEAP SUMMARY:
==17401== in use at exit: 73,519 bytes in 31 blocks
==17401== total heap usage: 36 allocs, 5 frees, 91,199 bytes allocated
==17401==
==17401== 1 bytes in 1 blocks are definitely lost in loss record 1 of 12
==17401== at 0x4C284B7: operator new[](unsigned long) (in
/usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==17401== by 0x401BB3: songlist::readList(std::basic_ifstream<char,
std::char_traits<char> >&)
The rest just kind of repeats itself through 12 of 12
My code:
defs.cpp:
#includes <iostream>
#include <cstring>
#include <iomanip>
#include <fstream>
#include "proj4.h"
using namespace std;
void songlist::makeList()
{
MAX_TRAX = 0;
song = new char**[20];
for (int i=0; i<20; i++)
{
song[i] = new char*[5];
}
}
void songlist::readList(ifstream& infile)
{
int counter = 0;
if (!infile.is_open())
{
cout << "Cannot open file: songs.txt";
}
while(!infile.eof())
{
infile >> newSong.title >> newSong.artist >>
newSong.durationMin >> newSong.durationSec >> newSong.album;
int i = strlen(newSong.title);
i++;
int j = strlen(newSong.artist);
j++;
int k = strlen(newSong.durationMin);
k++;
int l = strlen(newSong.durationSec);
l++;
int m = strlen(newSong.album);
m++;
if(i>0)
{
song[counter][0]= new char[i];
song[counter][1]= new char[j];
song[counter][2]= new char[k];
song[counter][3]= new char[l];
song[counter][4]= new char[m];
song[counter][0] = newSong.title;
song[counter][1] = newSong.artist;
song[counter][2] = newSong.durationMin;
song[counter][3] = newSong.durationSec;
song[counter][4] = newSong.album;
counter++;
}
MAX_TRAX = counter-1;
}
counter = 0;
}
void songlist::saveList(ofstream& outfile)
{
if (!outfile.is_open())
{
cout << "Cannot find file: songs.txt";
}
for (int i=0; i<=MAX_TRAX; i++)
{
outfile << song[i][0] << "; " << song[i][1] << "; " << song[i]
[2] << "; " <<song[i][3] << "; " << song[i][4] << ";" << endl;
}
}
void songlist::displayList()const
{
cout << left << setw(16) << '#' << left << setw(30) << "Song Name" <<
left << setw(22) << "Artist Name" << left << setw(17) << "Duration" <<
left << setw(20) << "Album Title" << endl;
cout << left << setw(110) << setfill ('-') << '-' << endl;
cout << setfill (' ');
if (strlen(newSong.title)>=1)
{
for (int i=0; i<=MAX_TRAX; i++)
{
cout << left << setw(4) << i+1 << left << setw(31) <<
song[i][0] << left << setw(31) << song[i][1] << right << setw(4) << song[i]
[2]
<< ':';
if (strlen(song[i][3])==1)
{
cout << '0';
cout << left << setw(3) << song[i][3] <<
left << setw(3) << song[i][4] << endl;
}
else
cout << left << setw(4) << song[i][3] << left <<
setw(3) << song[i][4] << endl;
}
cout << left << setw(110) << setfill ('-') << '-' << endl;
cout << setfill (' ');
}
}
void songlist::addSong()
{
if(strlen(newSong.title)>=1)
{
MAX_TRAX++;
}
cout << "Add a Song" << endl;
cout << endl;
cout << "Enter Song Title: ";
cin.ignore();
cin.get(newSong.title, 30);
cout << endl;
cout << "Enter Artist Name: ";
cin.ignore();
cin.get(newSong.artist, 30);
cout << endl;
cout << "Enter Track Duration";
cout << endl;
cout << "Minutes: ";
cin.ignore();
cin.get(newSong.durationMin, 3);
cout << endl;
cout << "Seconds: ";
cin.ignore();
cin.get(newSong.durationSec, 3);
cout << endl;
cout << "Enter Album Title: ";
cin.ignore();
cin.get(newSong.album, 30);
cout << endl;
cout << "Song Added to Database!";
cout << endl;
cout << endl;
int i = strlen(newSong.title);
i++;
int j = strlen(newSong.artist);
j++;
int k = strlen(newSong.durationMin);
k++;
int l = strlen(newSong.durationSec);
l++;
int m = strlen(newSong.album);
m++;
song[MAX_TRAX][0]= new char[i];
song[MAX_TRAX][1]= new char[j];
song[MAX_TRAX][2]= new char[k];
song[MAX_TRAX][3]= new char[l];
song[MAX_TRAX][4]= new char[m];
song[MAX_TRAX][0] = newSong.title;
song[MAX_TRAX][1] = newSong.artist;
song[MAX_TRAX][2] = newSong.durationMin;
song[MAX_TRAX][3] = newSong.durationSec;
song[MAX_TRAX][4] = newSong.album;
}
void songlist::removeSong()
{
int p = 0;
int q = 0;
int n = 0;
cout << "Remove a Song" << endl;
cout << "Enter Track Number to Confirm Deletion: ";
cin >> n;
cout << endl;
while (!(n >=1 && n <= MAX_TRAX+1))
{
cin.clear();
cin.ignore();
cout << "Must be a number between 1 and " << MAX_TRAX+1 << endl;
cout << "Enter Track Number to Confirm Deletion: ";
cin >> n;
cout << endl;
}
n--;
for (p=n;p<MAX_TRAX; p++)
{
for(q=0;q<5;q++)
{
delete[] song[p][q];
}
int i = strlen(song[p+1][0]);
i++;
int j = strlen(song[p+1][1]);
j++;
int k = strlen(song[p+1][2]);
k++;
int l = strlen(song[p+1][3]);
l++;
int m = strlen(song[p+1][4]);
m++;
song[p][0] = new char[i];
song[p][1] = new char[j];
song[p][2] = new char[k];
song[p][3] = new char[l];
song[p][4] = new char[m];
song[p][0] = song[p+1][0];
song[p][1] = song[p+1][0];
song[p][2] = song[p+1][0];
song[p][3] = song[p+1][0];
song[p][4] = song[p+1][0];
}
MAX_TRAX--;
n++;
cout << "Track Number " << n << " Deleted" << endl;
}
void songlist::searchList()const
{
int i;
char aOrB;
int counter = 0;
char art[30];
char alb[30];
cout << "Search by (a)rtist or al(b)um? (a or b): ";
cin >> aOrB;
cout << endl;
if (aOrB != 'a' && aOrB != 'b')
{
cout << "(a or b): ";
cin >> aOrB;
cout << endl;
}
if (aOrB == 'a')
{
cout << "Artist Name: ";
cin.ignore();
cin.get(art, 30);
for(i=0; i<=(MAX_TRAX); i++)
{
if (strcmp(art, song[i][1])==0)
{
cout << left << setw(2) << i+1 << left <<
setw(32) << song[i][0] << left << setw(32) << song[i][1] << right << setw(4)
<< song[i][2] << ':' << left << setw(5) << song[i][3] << left << setw(32) <<
song[i][4] << endl;
counter++;
}
}
}
else
{
cout << "Album Name: ";
cin.ignore();
cin.get(alb, 30);
for(i=0; i<=(MAX_TRAX); i++)
{
if (strcmp(alb, song[i][4])==0)
{
cout << left << setw(2) << i+1 << left <<
setw(32) << song[i][0] << left << setw(32) << song[i][1] << right << setw(4)
<<
song[i][2] << ':' << left << setw(5) << song[i][3] << left << setw(32) <<
song[i][4] << endl;
counter++;
}
}
}
if (!counter)
{
cout << endl;
cout << "No Matches Found; check spelling and/or case." << endl;
}
}
void songlist::deleteAll()
{
for(int i=0; i>=20; i++)
{
for (int j=0; j<5; j++)
delete[] song[i][j];
delete[] song[i];
}
delete[] song;
}
songlist::songlist()
{
}
Proj4.h:
#ifndef PROJ3_H
#define PROJ3_H
#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
using namespace std;
class songlist
{
public:
void readList(ifstream& infile);
void saveList(ofstream& outfile);
void displayList() const;
void makeList();
void addSong();
void removeSong();
void searchList() const;
void deleteAll();
songlist();
private:
struct songs
{
char title[30] = {'\0'};
char artist[30] = {'\0'};
int intMin = 0;
int intSec = 0;
char durationMin[3] = {'\0'};
char durationSec[3] = {'\0'};
char album[30] = {'\0'};
};
songs newSong;
int MAX_TRAX;
char *** song;
};
#endif
app.cpp:
#include <iostream>
#include <cstring>
#include <iomanip>
#include <fstream>
#include "proj4.h"
using namespace std;
int main()
{
char selection;
cout << endl;
cout << "*Music Track Database*" << endl;
ifstream infile;
ofstream outfile;
infile.open("songs.txt");
outfile.open("songs.txt");
songlist newlist;
newlist.makeList();
do
{
cout << endl;
cout << "Main Menu:" << endl;
cout << endl;
cout << "(a)dd a song" << endl;
cout << "(r)emove a song" << endl;
cout << "(d)isplay track listings" << endl;
cout << "(s)earch for a track" << endl;
cout << "(q)uit" << endl;
cout << endl;
cout << "Select (a, r, d, s, q): ";
cin >> selection;
cout << endl;
if (selection != 'a' && selection != 'r' && selection != 'd'
&& selection != 's' && selection != 'q')
{
cout << "Select (a, r, d, s, q): ";
cin >> selection;
cout << endl;
}
switch (selection)
{
case 'a':
newlist.readList(infile);
newlist.addSong();
newlist.saveList(outfile);
break;
case 'd':
newlist.readList(infile);
newlist.displayList();
break;
case 'r':
newlist.removeSong();
newlist.saveList(outfile);
break;
case 's':
newlist.readList(infile);
newlist.searchList();
break;
}
}while (selection != 'q');
newlist.deleteAll();
cout << "Happy Trails To You; Until We Meet Again!" << endl;
cout << endl;
infile.close();
outfile.close();
return 0;
}
Also here is a simple makefile to test it:
all:
g++ app.cpp proj4.h defs.cpp -o proj4;
clean:
clean make;
Anything helps!
Thank You in advance.
You're not even allowed to use structs or classes? When you become a three star programmer it's usually very bad.
Your allocations are off by one (null termination...)
But the actual leak is here. Just think what this does:
song[p][0] = new char[i];
song[p][1] = new char[j];
song[p][2] = new char[k];
song[p][3] = new char[l];
song[p][4] = new char[m];
song[p][0] = song[p+1][0];
song[p][1] = song[p+1][0];
song[p][2] = song[p+1][0];
song[p][3] = song[p+1][0];
song[p][4] = song[p+1][0];
You first allocate memory and then throw the pointers away by assigning something else to those pointers. You can never get them back and that's a leak.
Instead of this:
song[counter][0] = new char[i];
song[counter][1] = new char[j];
song[counter][2] = new char[k];
song[counter][3] = new char[l];
song[counter][4] = new char[m];
song[counter][0] = newSong.title;
song[counter][1] = newSong.artist;
song[counter][2] = newSong.durationMin;
song[counter][3] = newSong.durationSec;
song[counter][4] = newSong.album;
Maybe Something more like:
song[counter][0] = new char[i];
song[counter][1] = new char[j];
song[counter][2] = new char[k];
song[counter][3] = new char[l];
song[counter][4] = new char[m];
strncpy(song[counter][0], newSong.title, i);
strncpy(song[counter][0], newSong.artist, j);
strncpy(song[counter][0], newSong.durationMin, k);
strncpy(song[counter][0], newSong.durationSec, l);
strncpy(song[counter][0], newSong.album, m);
Related
This question already has answers here:
What is array to pointer decay?
(11 answers)
Array Size Member Function Compile Error
(3 answers)
Closed 15 days ago.
I get an error saying "'find' in ‘sentence’, which is of non-class type ‘char*’".
So the instruction was to enter a string and identify which in the string is a noun, pronoun, adjectives and a linking verb. Everything seems to work except the ".find" part. I really need help.
(btw, nvm the other unecessary things. I made the code shorter to put focus more on the problem)
#include <iostream>
#include <cstring>
#include <cctype>
#include <string>
using namespace std;
string student_id, first_name, last_name, middle_name, suffix;
char sentence[100][100];
char history1[100][100];
int h = 0, s= 0;
char noun[20][20] = {"Ervin", "Rafi", "Peco", "luis", "Edgar", "Benj", "Rias", "Aki", "Naruto", "Jhay", "Josh", "Jopay", "Sasuke", "Joshua", "Trump", "Benjo", "Alice", "Janelle", "Samantha", "Jairah"};
char pronoun[20][20] = {"he", "she", "i", "it", "you"};
char verb[20][20] = {"is", "was", "are", "as", "am"};
char adj[20][20] = {"big", "small", "racist", "fat", "Funny", "gay", "black", "white", "rainbow", "tiny", "smart", "bi", "pan", "stupid", "idiot", "buang", "retard", "gaymer", "special", "talented"};
void display_dictionary();
void open_checker();
bool hasElement(char sentence[], char elements[], int size);
int main()
{
int option;
cout << endl << "Account Menu" <<endl;
cout << "[1] Open checker" << endl;
cout << "[2] Display Dictionary" << endl;
cout << "Option: ";
cin >> option;
switch (option){
case 1: open_checker(); break;
case 2: display_dictionary(); break;
}
return 0;
}
void display_dictionary(){
cout << "List of Nouns: ( ";
for (int n = 0; n < 20; n++){
cout << noun[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Pronouns: ( ";
for (int n = 0; n < 5; n++){
cout << pronoun[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Linking Verbs: ( ";
for (int n = 0; n < 5; n++){
cout << verb[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Adjectives: ( ";
for (int n = 0; n < 20; n++){
cout << adj[n] << " " ;
}
cout << ")" << endl << endl;
}
void open_checker(){
int option;
cout << "Enter Sentence: ";
cin.ignore();
cin.get(sentence[s], 100);
if (hasElement(sentence[s], noun[s], 20)){
cout << " Is a noun." << endl;
}
if (hasElement(sentence[s], adj[s], 20)){
cout << " Is an Adjectives." << endl;
}
if (hasElement(sentence[s], verb[s], 5)){
cout << " Is a Linking Verb." << endl;
}
if (hasElement(sentence[s], pronoun[s], 5)) {
cout << " Is a Linking Verb." << endl;
}
else {
cout << "Sentence does not have all required elements." << endl;
}
strcpy(history1[h], sentence[s]);
history1[h][h] = sentence[s][s];
h++;
s++;
cout << "Type 1 to go back: ";
cin >> option;
if (option == 1){
main();
}
}
bool hasElement(char sentence[], char elements[], int size){
for (int i = 0; i < size; i++) {
if (sentence.find(elements[i]) != string::npos) {
cout << elements[i];
return true;
}
}
return false;
}```
This is my code at the moment. It is a lottery game and I get user input for 7 numbers and do not allow duplicates (same goes with the random generated). I need to display the user's numbers and the winning random numbers at the end of the main next to LOTTO RESULTS and WINNING NUMBERS.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
cout << name << "'s TICKET : " << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
It seems you might be new to programming so here you go, your working program:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
for(int i = 0; i < size; i++){
cout << WinningNums[i] << " ";
}
cout << endl;
cout << name << "'s TICKET : " << endl;
for(int i = 0; i < size; i++){
cout << UserTicket[i] << " ";
}
cout << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
As you can see, it is pretty easy to loop through an array. Maybe have a look at this for more info on arrays.
Most of the examples show "classic" C++, instead of the more modern variants.
So here's my take on your code :
#include <algorithm>
#include <array>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
// compile time constant, in many C++ examples this is done with a #define/MACRO
constexpr int number_of_lotto_numbers = 7;
constexpr char play_lotto_char = '1';
constexpr char quit_lotto_char = 'q';
// use std::array instead of int values[]; since this has automatic bound checking!
// no reading/writing beyond array limits is allowed
// I use, using here to make code a bit more readable further down the line
// it lets code show intent instead of implementation
using lotto_numbers_t = std::array<int, number_of_lotto_numbers>;
// do not return arrays by passing arguments, just return an array
// don't worry about this making extra (class) copies c++ knows how to optimize this
lotto_numbers_t get_lotto_picks()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_entered{ 0 };
while ( lotto_numbers_entered < number_of_lotto_numbers )
{
int input{ 0 };
std::cout << "selection #" << lotto_numbers_entered + 1 << ": " << std::endl;
std::cin >> input;
// use std::find for finding items in collections, if it finds the end of a collection then
// the value is not found.
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), input) == lotto_numbers.end())
{
// lotto number not found so add it
lotto_numbers[lotto_numbers_entered] = input;
lotto_numbers_entered++;
}
else
{
// lotto number already in array so do not add it but give a message
std::cout << "You already entered this number, try another number" << std::endl;
}
}
return lotto_numbers;
}
lotto_numbers_t generate_winning_numbers()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_generated{ 0 };
std::srand((unsigned int)time(NULL));
do
{
int new_number = (std::rand() % 40) + 1;
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), new_number) == lotto_numbers.end())
{
// number not yet found
lotto_numbers[lotto_numbers_generated] = new_number;
lotto_numbers_generated++;
}
} while (lotto_numbers_generated < number_of_lotto_numbers);
return lotto_numbers;
}
void play_lotto()
{
char selection{ 0 }; // always initialize variables!
std::string name;
do
{
std::cout << "LITTLETON CITY LOTTO MODEL: " << std::endl;
std::cout << "---------------------------" << std::endl;
std::cout << "1) Play Lotto" << std::endl;
std::cout << "q) Quit Program" << std::endl;
std::cout << "Please make a selection : " << std::endl;
std::cin >> selection;
if (selection == play_lotto_char)
{
std::cout << "Please enter your name: " << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
auto picked_numbers = get_lotto_picks();
auto winning_numbers = generate_winning_numbers();
std::cout << name << "'s LOTTO RESULTS" << std::endl;
std::cout << "----------------------" << std::endl;
std::cout << "WINNING TICKET NUMBERS : " << std::endl;
for (const auto number : winning_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
std::cout << name << "'s TICKET : " << std::endl;
for (const auto number : picked_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
if (picked_numbers == winning_numbers)
{
std::cout << "you have won!" << std::endl;
}
}
else if (selection == quit_lotto_char)
{
std::cout << "You have chosen to quit the program. Thank you for using!" << std::endl;
}
else
{
std::cout << "Invalid selection. Please try again." << std::endl;
}
} while (selection != quit_lotto_char);
}
Don't hesitate to ask questions on this code if you have any :)
I was able to write a program to pass my c++ class in college except for one feature. I was unable to create a function that sorted the names inside an array of structs with name of type char alphabetically. Please advise on how to tackle this problem.
I would need a function that sorts the accountRecords array alphabetically.
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
//Structure Initilizations
const int NAME_SIZE = 25, ADDR_SIZE = 100, CITY_SIZE = 51, STATE_SIZE = 4, DATE_SIZE = 16, CUSTOMER_ID = 10, TRANSACTION_TYPE = 16;
struct MasterRecord
{
int customerID;
char name[NAME_SIZE]; // SORT THIS FIELD ALPHABETICALLY
char address[ADDR_SIZE];
char city[ADDR_SIZE];
char state[STATE_SIZE];
char zip[STATE_SIZE];
float accountBalance;
char lastTransactionDate[15];
};
struct TransactionRecord
{
int customerID;
char transactionType;
float amount;
char transactionDate[15];
};
//File Array Initializations
vector<MasterRecord> masterRecordList(101);
vector<TransactionRecord> transRecordList(101);
//Array List Record Position
int masterRecordArrayPosition = 0;
int transactionRecordArrayPosition = 0;
//User Menu Answer Variable Initialization
int userAnswer = 0;
string recordNotFoundAnswer = "";
//Print Function Prototypes
void showMenu();
void showMasterRecord(int);
void showTransactionRecord(int);
//Main Menu Function Prototypes
void newCustomerRecord(int);
void editCustomerRecord(int);
void deleteCustomerRecord(int);
int randomComputerID();
int searchMasterRecord(int);
void saveAccountRecords();
void saveTransRecords();
void newTransactionRecord(int);
//Placeholders Variables
int customerIDsearch = 0;
int customerIDSearchArrayPosition = 0;
int userNameCharactererror = 0;
//Function Loop Counters
int accountWriteCounter = 0;
int transWriteCounter = 0;
int showRecordCounter = 0;
int showTransCounter = 0;
//System time Declaration and Conversion for [lastTransactionDate]
time_t now = time(0);
tm *ltm = localtime(&now);
string currentYearInString = to_string(1900 + ltm->tm_year);
string currentMonthInString = to_string(1 + ltm->tm_mon);
string currentDayInString = to_string(ltm->tm_mday);
string currentDateInString = currentMonthInString + "/" + currentDayInString + "/" + currentYearInString;
char dateInChar[15];
//Main Program
int main()
{
//Final conversion of time in string to char for storage
strncpy_s(dateInChar, currentDateInString.c_str(), 15);
//Open MasterRecord file and read records to arrays
fstream masterRecord("masterRecord.dat", ios::in | ios::binary);
int listCounter = 0;
if (!masterRecord) {
cout << "Unable to open the user records file, creating file database....Done!" << endl;
masterRecord.open("masterRecord.dat", ios::out | ios::binary);
}
else {
while (!masterRecord.eof()) {
masterRecord.read(reinterpret_cast<char *>(&masterRecordList[listCounter]), sizeof(masterRecordList[0]));
if (masterRecordList[listCounter].customerID != 0) {
listCounter++;
}
masterRecordArrayPosition = listCounter;
}
masterRecord.close();
}
//Open Transaction Record and read to arrays
fstream transactionRecord("transactionRecord.dat", ios::in | ios::binary);
int listCounter2 = 0;
if (!transactionRecord) {
cout << "Unable to open the transaction file, creating file database....Done!" << endl << endl;
transactionRecord.open("transactionRecord.dat", ios::out | ios::binary);
}
else {
while (!transactionRecord.eof()) {
transactionRecord.read(reinterpret_cast<char *>(&transRecordList[listCounter2]), sizeof(transRecordList[0]));
if (transRecordList[listCounter2].customerID != 0) {
listCounter2++;
}
transactionRecordArrayPosition = listCounter2;
}
transactionRecord.close();
}
//Time Declaration Used to Generate Random IDs
srand((unsigned)time(0));
//Main user Program Loop
while (userAnswer != 6) {
showMenu();
cin >> userAnswer; cout << endl;
//Menu Input Data Validation
if (cin.fail()) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
cin.clear();
cin.ignore();
}
else {
if (userAnswer < 1 || userAnswer > 7) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
userAnswer = 0;
}
}
//Menu Selection Switch Case
switch (userAnswer) {
case 1:
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
break;
case 2:
newTransactionRecord(transactionRecordArrayPosition);
break;
case 3:
cout << "Please enter the Customer ID you would like to Delete" << endl << endl; //[Delete Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
deleteCustomerRecord(customerIDSearchArrayPosition);
}
break;
case 4:
cout << "Please enter the Customer ID you would like to edit." << endl << endl; //[Search/Edit Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
editCustomerRecord(customerIDSearchArrayPosition);
}
else {
cout << "Record was not found, would you like to add a new record? Y = Yes, N = No" << endl << endl;
cin >> recordNotFoundAnswer;
if (recordNotFoundAnswer == "Y" | recordNotFoundAnswer == "y") {
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
}
else if (recordNotFoundAnswer == "N" | recordNotFoundAnswer == "n") {
userAnswer = 0;
}
}
break;
case 5:
cout << setw(212) << "Please find all customer records in the database" << endl << endl; //[Show all Records] Function goes here
cout << setw(40) << "Name:" << setw(10) << "ID:" << setw(23) << "Street Address:" <<setw(10) << "ZIP:" << setw(16) << "L.Trans Date:" << setw(11) << "Balance: " << endl;
while (showRecordCounter < 100) {
if (masterRecordList[showRecordCounter].customerID != 0) {
showMasterRecord(showRecordCounter);
}
showRecordCounter = showRecordCounter + 1;
} showRecordCounter = 0;
userAnswer = 0;
cout << endl;
break;
case 6:
cout << "Saving changes to database...Done!" << endl;
saveAccountRecords();
saveTransRecords();
cout << "Done!" << endl;
break;
case 7:
cout << "Showing all transaction Records:" << endl << endl;
while (showTransCounter < 100) {
if (transRecordList[showTransCounter].customerID != 0) {
showTransactionRecord(showTransCounter);
}
showTransCounter = showTransCounter + 1;
} showTransCounter = 0;
userAnswer = 0;
break;
}
}
return 0;
}
//Databas Management Functions
void saveAccountRecords() {
fstream masterRecord("masterRecord.dat", ios::out | ios::binary);
while (accountWriteCounter < 100) {
masterRecord.write(reinterpret_cast<char *>(&masterRecordList[accountWriteCounter]), sizeof(masterRecordList[0]));
accountWriteCounter++;
}
masterRecord.close();
}
void saveTransRecords() {
fstream transRecord("transactionRecord.dat", ios::out | ios::binary);
while (transWriteCounter < 100) {
transRecord.write(reinterpret_cast<char *>(&transRecordList[transWriteCounter]), sizeof(transRecordList[0]));
transWriteCounter++;
}
transRecord.close();
}
//Random Function
int randomComputerID() {
int randomNumber;
randomNumber = (rand() % 1000) + 10000;
return randomNumber;
}
//Program Print Functions
void showMenu() {
cout << "Welcome to your C++ company terminal! Please enter one of the options below to continue." << endl << endl;
cout << "1. New Customer Record" << endl;
cout << "2. New Transaction Record" << endl;
cout << "3. Delete Customer Record" << endl;
cout << "4. Edit Customer Record" << endl;
cout << "5. Show all Account Records in Database" << endl;
cout << "6. Exit and Save Changes to Database" << endl << endl;
cout << "Please enter the number for the correspondent action you would like to perform:" << endl;
}
void showMasterRecord(int arrayNum) {
cout << setw(40)
<< masterRecordList[arrayNum].name << setw(10) << masterRecordList[arrayNum].customerID << setw(23)
<< masterRecordList[arrayNum].address << setw(10)
<< masterRecordList[arrayNum].zip << setw(16)
<< masterRecordList[arrayNum].lastTransactionDate << setw(6) <<"$"
<< masterRecordList[arrayNum].accountBalance; cout << endl;
}
void showTransactionRecord(int arrayNum) {
cout << "Customer ID: " << transRecordList[arrayNum].customerID << endl;
cout << "Amount: $" << transRecordList[arrayNum].amount << endl;
cout << "Transaction Type: " << transRecordList[arrayNum].transactionType << endl;
cout << "Transaction Date: " << transRecordList[arrayNum].transactionDate << endl << endl;
}
//Main Menu Functions [Please insert your functions here and prototype them above].
void newCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
masterRecordList[arrayNum].customerID = randomComputerID();
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
do
{
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 25);
if (cin.fail()) {
cout << endl << "Please enter only characters up 25 chracters for your name." << endl;
userNameCharactererror = 1;
cin.clear();
cin.ignore(80, '\n');
}
else {
userNameCharactererror = 0;
}
} while (userNameCharactererror == 1);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Opening Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
masterRecordArrayPosition = masterRecordArrayPosition + 1;
}
void editCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 51);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Edit Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
}
void deleteCustomerRecord(int arrayNum) {
if (masterRecordList[arrayNum].accountBalance == 0)
{
masterRecordList[arrayNum].customerID = 0;
cout << "Record has been deleted" << endl << endl;
}
else {
cout << "Unable to delete record, customer accounts holds a positive balance" << endl << endl;
}
}
int searchMasterRecord(int customerID) //Search by customer name and returns array position
{
int arrayPosition = 0;
int arrayCounter = 0;
int customerIdPlaceholder = 0;
while (arrayCounter < 100) {
customerIdPlaceholder = masterRecordList[arrayCounter].customerID;
if (customerIdPlaceholder == customerID) {
cout << "Record has been found!" << endl << endl;
arrayPosition = arrayCounter;
arrayCounter = 100;
}
else {
arrayPosition = 9999;
}
arrayCounter = arrayCounter + 1;
}
return arrayPosition;
};
void newTransactionRecord(int arrayNum) {
// Request customer ID and transaction type from the user
cout << "Customer ID: ";
cin >> transRecordList[arrayNum].customerID;
cin.ignore();
cout << "Date: ";
strncpy_s(transRecordList[arrayNum].transactionDate, dateInChar, 15);
cout << transRecordList[arrayNum].transactionDate << endl;
cout << "Transaction Type [D = Deposit] [W = Withdrawal]: ";
cin >> transRecordList[arrayNum].transactionType;
cout << "Amount: $";
cin >> transRecordList[arrayNum].amount;
//Search for customer account, update balance, and assign last transaction date
customerIDSearchArrayPosition = searchMasterRecord(transRecordList[arrayNum].customerID);
if (customerIDSearchArrayPosition != 9999) {
if (transRecordList[arrayNum].transactionType == 'D') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance + transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Deposit Successful! " << endl << endl;
}
else if (transRecordList[arrayNum].transactionType == 'W') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance - transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Withdrawl Successful" << endl << endl;
}
}
else {
cout << "Customer account record was not found, transaction was not saved." << endl << endl;
}
transactionRecordArrayPosition = transactionRecordArrayPosition + 1;
}
Something along these lines:
std::sort(masterRecordList.begin(),
masterRecordList.begin() + masterRecordArrayPosition,
[](const MasterRecord& l, const MasterRecord& r) {
return strcmp(l.name, r.name) < 0;
});
I am studying BscCS so I am familiar with programming concepts, however I always seem to get stuck on structs and arrays of structs.
I am required to convert parallel arrays into an array of structs. I have done this, but for some reason the information is not getting sent to the functions properly and the program keeps crashing.
Could you help identify where I am going wrong of if there is something I am missing? I don't need exact code for answers, just some guidance. Here is the code:
#define SIZE 3
struct Employee {
string firstName[SIZE];
string lastName[SIZE];
int id[SIZE];
int hoursWorked[SIZE];
int payRate[SIZE];
int stat[SIZE];
};
//Functions
int menu();
void printReport(Employee & employees);
void search(Employee & employees);
void calculatePay(Employee & employees);
void orderByLastName(Employee & employees);
void orderByid(Employee & employees);
void printActive(Employee & employees);
void printInactive(Employee & employees);
//Display Main Menu
int menu()
{
int choice;
cout << "1. Print out Employee Report. " << endl;
cout << "2. Search Employee Records. " << endl;
cout << "3. Display the Report in Sorted order on Last Name or ID. << endl;
cout << "4. Calculate Pay. " << endl;
cout << "5. Display Active Employees." << endl;
cout << "6. Display Inactive Employees." << endl;
cout << "7. Quit" << endl;
cout << "Enter your choice. ";
cin >> choice;
return choice;
}
//Display the employee data in a formatted order
void printReport(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] << endl;
}
//Search for employee ID
//Show "Not Found" if unable to locate
void search(Employee & employees)
{
bool found = false;
int idNumber;
int pos = -1;
cout << "Enter id number ";
cin >> idNumber;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.id[index] == idNumber)
{
found = true;
pos = index;
}
}
if (!found)
cout << "Not Found. " << endl;
else
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
//Calculate total weekly pay
void calculatePay(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
setw(10) << "Total Pay" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] <<
setw(10) << employees.hoursWorked[index] * employees.payRate[index] << endl;
}
//Sort employee data by last name
void orderByLastName(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.lastName[j] > employees.lastName[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
//Sort employee data by ID
void orderByid(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.id[j] > employees.id[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
void printActive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 1)
{
found = true;
pos = index;
}
if (!found) {
cout << "No active employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
void printInactive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 0)
{
found = true;
pos = index;
}
if (!found) {
cout << "No inactive employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
int main()
{
struct Employee employees[SIZE];
//Read first and last name from user
for (int index = 0; index < SIZE; index++)
{
cout << "Enter first name : ";
cin >> employees[index].firstName[index];
cout << "Enter last name : ";
cin >> employees[index].lastName[index];
//Read ID, hours, and pay rate from user
while (employees[index].id[index] < 0)
{
cout << "Enter id : ";
cin >> employees[index].id[index];
if (employees[index].id[index] < 0)
{
cout << "Invalid Id number. " << endl;
cout << "Enter id : ";
cin >> employees[index].id[index];
}
}
while (employees[index].hoursWorked[index] < 0)
{
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
if (employees[index].hoursWorked[index] < 0)
{
cout << "Invalid hours. " << endl;
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
}
}
while (employees[index].payRate[index] < 0)
{
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
if (employees[index].payRate[index] < 0)
{
cout << "Invalid pay rate. " << endl;
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
}
}
while (employees[index].stat[index] < 0)
{
cout << "Enter your status. (0 - Inactive, 1 - Active) : ";
cin >> employees[index].stat[index];
if (employees[index].stat[index] < 0)
{
cout << "Enter your status : ";
cin >> employees[index].stat[index];
}
cout << endl;
}
}
//Loop to display menu options until user quits program
while (true)
{
//Call menu with options
int ch = menu();
//Different options to choose
switch (ch)
{
case 1:
printReport(employees[SIZE]);
break;
case 2:
search(employees[SIZE]);
break;
case 3:
int sortType;
cout << "1.Sort by Last Name." << endl;
cout << "2.Sort by ID." << endl;
cout << "Enter your choice. ";
cin >> sortType;
if (sortType == 1)
orderByLastName(employees[SIZE]);
else if (sortType ==2)
orderByid(employees[SIZE]);
break;
case 4:
calculatePay(employees[SIZE]);
break;
case 5: printActive(employees[SIZE]);
case 6: printInactive(employees[SIZE]);
break;
case 7:
exit(0);
}
}
system("pause");
return 0;
}
Thank you in advance!
I ran your program, and I received more than 20 errors before the compiler involuntarily stopped trying to compile any longer. All of them are connected to the lines of code using cout, cin, string, and setw. You need to use these keywords with the std namespace to fix this, and you need to include the iostream header file (#include <iostream>). Either you can write std:: in front of all of these keywords (i.e. std::cout) or you can declare the namespace in the preprocessor (using namespace std;). Also, for std::setw, you need to include the iomanip header file (#include <iomanip>). After that, you're missing a quotation in the menu function and a bracket at the end of the main function. (There's also a couple of problems with initializing the size of the struct members in the declaration, but I'll leave that up to you.) Hope this helped!
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int instructions();
void manual();
void file(char*);
int letterFill(char, char*, char*);
void Unknown(char*, char*);
const int MAX_LENGTH = 10;
void main()
{
bool done = false;
char word[MAX_LENGTH];
char unknown[MAX_LENGTH];
char letter;
char name[MAX_LENGTH];
int wrong_guesses = 0;
int MAX_TRIES;
char ans;
while (!done)
{
switch (instructions())
{
case 1:
{
manual();
break;
}
case 2:
{
file(word);
break;
}
}
cout << "WHAT IS THE NUMBER OF GUESSES ALLOWED?: " << endl;
cin >> MAX_TRIES;
Unknown(word, unknown);
cout << endl << endl << "HANGMAN";
cout << endl << endl << "Each letter is represented by a star." << endl;
cout << "You have " << MAX_TRIES << " tries left.";
cout << "ENTER GUESS WHEN READY: ";
cin >> letter;
while (letter != 'N' && letter != 'n')
{
while (wrong_guesses < MAX_TRIES)
{
cout << unknown << endl;
cout << "Guess a letter: " << flush;
cin >> letter;
if (letterFill(letter, word, unknown) == 0)
{
cout << endl << "You got it wrong! You lose a guess" << endl;
wrong_guesses++;
}
else
{
cout << endl << "Pfft, you got lucky" << endl;
}
cout << "Guesses Left: " << MAX_TRIES - wrong_guesses << endl;
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You got it!" << endl;
exit(0);
}
cout << "You've been hanged." << endl;
cout << "The word was : " << word << endl;
}
}
cout << "Try again? (y/n): " << flush;
cin >> ans;
if (ans == 'y' || ans == 'Y')
done = true;
else
done = false;
}
system("pause");
}
int instructions()
{
int select = 0;
cout << endl << "HANGMAN" << endl << endl;
cout << " PROGRAM MENU" << endl;
cout << " Select option 1 or 2" << endl << endl;
cout << " 1. INPUT WORD MANUALLY" << endl;
cout << " 2. PLAY AGAINST THE COMPUTER" << endl;
cout << " 3. EXIT PROGRAM BY INPUTING: N or n" << endl << endl;
cin >> select;
return select;
}
void manual()
{
string word;
cout << endl << "INPUT WORD: " << endl;
cin >> word;
return;
}
void file(char *roc)
{
ifstream fin("word.txt");
int x;
int count = 1;
int word;
int i = 0;
srand(time(0));
word = rand() % 20;
while (count < word)
{
fin >> x;
if (x == 0)
{
count++;
}
}
do
{
fin >> x;
roc[i++] = char(x);
} while (x);
return;
}
int letterFill(char guess, char *secretword, char *guessword)
{
int i;
int matches = 0;
for (i = 0; i<MAX_LENGTH; i++)
{
if (secretword[i] == 0)
{
break;
}
if (guess == guessword[i])
{
return 0;
}
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void Unknown(char *word, char *unknown)
{
int i;
int length = strlen(word);
for (i = 0; i<length; i++)
{
unknown[i] = '*';
}
unknown[i] = 0;
}
Again
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.