Project in c++, making a phonebook [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I tried and looked everywhere on the internet, I can't seem to find much.
Now, without too much talking, to the problem I have: I have to make a project for college that consists of making an "electronic phone-book" using OOP programming logic in C++. The materials I`ve received to do this are extremely vague so I must do on my own somehow.
Here is the code I have done so far(with help from the internet):
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include <string.h>
#include <fstream.h>
void op1()
{
printf("\n Add contact");
getch();
}
void op2()
{
printf("\n Delete contact");
getch();
}
void op3()
{
printf("\n Edit a contact");
getch();
}
void op4()
{
printf("\n Find a contact");
getch();
}
void op5()
{
printf("\n Sort the contacts");
getch();
}
void op6()
{
printf("\n 'About the program, details etc. etc.");
getch();
}
void print_menu()
{
system("cls"); // clearing window
printf("\nMenu:");
printf("\n##############################\n");
printf("\n1. Add contact");
printf("\n2. Delete contact");
printf("\n3. Edit a contact");
printf("\n4. Find a contact");
printf("\n5. Sort the contacts");
printf("\n6. About");
printf("\n7. Exit");
printf("\n\n##############################");
printf("\n\nInput your option: ");
}
// Text centering function - begin
void centerText(char* s)
{
int l=strlen(s);
int pos=(int)((80-l)/2);
for(int i=0;i<pos;i++)
cout<<" ";
cout<<s<<endl;
}
// Text centering functon - end
void main()
{
{
printf("\n 'My University' 'My City' ");
printf("\n Faculty of Electrical Engineer and Computer Science");
printf("\n Study program used: C++\n\n");
centerText("C++ Project");
centerText("<The Phonebook>");
printf("\n");
centerText("<my name, Year I of study, Group>");
printf("\n");
printf("\n");
centerText("<june.2013>");
system("pause>nul"); // Screen is paused until a key is pressed (to allow this text to be viewed)
}
// ... Sequence for password verification ...
{
char password[20], my_password[20]="2013";
system("cls");
printf("WARNING!\n");
printf("Authentication required!\n");
printf("\nType input password: ");
scanf("%19s",password);
if (strcmp(password, my_password)!=0)
{
printf("\n\nIncorrect password !!!\n");
printf("The program will now exit...\n");
getch();
return;
}
printf("\n\nPassword is correct !\n");
printf("The program is executed !\n");
getch();
}
char optiune;
// ... Sequence for option choosing ...
do
{
print_menu();
fflush(stdin);
cin>>optiune;
switch(optiune)
{
case '1': op1(); break;
case '2': op2(); break;
case '3': op3(); break;
case '4': op4(); break;
case '5': op5(); break;
case '6': op6(); break;
case '7': exit(0);
default : printf("\n\nIncorrect option !");
fflush(stdin);
getch();
}
}
while(1);
}
The idea was that I could maybe use this menu in a way like, just inserting in one of the op() functions the redirect to another file, which is 1 function in a separate file.
So I would then have this program as a main program and each function that "adds, edits, deletes ..etc will be outside of this program and I would deal with them separately.
Thing is ..I have no clue in doing so. I've looked in the "header" working system and I didn't really find anything of value there. Maybe I don't know to look but trust me I've really tried.
Any feedback is much appreciated, but remember I am extremely newbie in this. Please, if you can, explain with as much detail as you can. I appreciate anyone who read this entire thing. I will thank the beginning.

You say you can't find help anywhere, but then you say "I have to make a project for college". So presumably you already have instructors and/or professors to help you learn? Other than that, any introductory C++ book ever written will cover what you're asking for, here.
You say "using OOP programming logic in C++", yet you don't use any OOP other than built in IO classes.
Indent your code properly.
Don't use these:
#include <conio.h>
getch()
system("cls")
You're mixing calls to printf() with std::cout, and calls to scanf() with std::cin - pick one or the other, and never use scanf().
If you're using C++, using std::string is better than this:
void centerText(char* s)
The cast here is unnecessary, when you're assigned to an int it'll automatically convert:
int pos=(int)((80-l)/2);
main() returns int, don't do this:
void main()
You can't fflush(stdin), flushing is not defined on input streams.
Don't put things on one line like this, because it looks awful:
case '1': op1(); break;
It's better to return 0 than exit(0) under normal circumstances, as exit(0) will not destroy your objects.

In many applications there are three main components to building the solution. There is the View, which is how you interact with the user. Your work so far looks as though you are building a fairly sensible command line interface for that. Then there is the back end where the contacts will be stored. This could be a file, a database or some kind of JSON or XML structure. In between is the controller that keeps the view and database in sync and executes commands and queries from the user. Maybe this is going too far for your coursework and you are happy if everything is forgotten when you kill the program. In that case you need a memory-based structure to hold the data. I suggest you make a class to hold all the fields in your contact and store in in a std::vector<Contact>.

Related

Calculator Program does not compile [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I wrote a program that implements a simple calculator. However, it does not compile. The compiler says that there are 22 errors, and I don't know why.
Desired behavior:
Asks user about the desired operation
Asks user about the parameters
Outputs result
Specific problem or error:
Compilation errors at any occurrence of cin,cout, endl, case and break
Minimal, Complete, and Verifiable example:
#include <iostream>
int main()
{
float area, r, l, h, b;
int choice;
cout<<"\n area of?";
cout<<"\n[1]square \n[2]rectangle \n[3]circle \n[4]triangle"<<endl;
cin>>choice;
switch(choice);
{
case 1:
cout<<"enter length"<<endl;
cin>>l;
area=l*l;
cout<<area<<endl;
break;
case 2:
cout<<"enter height"<<endl;
cin>>h;
cout<<"enter length"<<endl;
cin>>l;
area=l*h;
cout<<area<<endl;
break;
case 3:
cout<<"enter radius"<<endl;
cin>>r;
area=r*r*3.14;
cout<<area<<endl;
break;
case 4:
cout<<"enter height"<<endl;
cin>>h;
cout<<"enter breadth"<<endl;
cin>>b;
area=h*b*0.5;
cout<<area<<endl;
break;
}
return 0;
}
The are two errors (compile time errors, at least). First of all, cin, cout and endl are not known, you have to write them as std::cin, std::cout and std::endl.
The second problem is here:
switch (choice);
Remove that semicolon and it's fine. The reson why it's not working with the semicolon is because then switch (choice); is its own one and done deal, and the statements after it don't make sense without it.
Also, although it's not causing any compile time errors, I would highly recommend that you indent your code properly. mjcs edited the code you provided for you, it now looks much nicer and it is much easier to find the errors this way. In a big program, it is absolutely vital that the code is indented well, otherwise it's very hard to work with.

C++ - Using specific character input for 'if' statements

I am, for lack of a better word, an absolute programming novice. And as it stands, I've been flung head first into programming something in two or three languages.
As part of an assignment, we have been tasked with essentially recreating a heads/tails flip, in the form of a random chance game.
The way it works is the player has ten credits to start off with. They are asked to input a wager, and then they are asked heads or tails. Picking either heads or tails sets off a number generator, and depending on the value, they may well end up winning or losing their wager.
I coded a similar version of this using HTML/CSS/JS, and it works. I'll leave a puush link to the file so you can view it yourselves to get an idea of what I'm trying to do: http://puu.sh/bP2V7/2ef63f4a1c.html
I'm trying to do, functionally, the same thing in C++ in the form of a command application. I know the code I'm using works fine, and it compiles without much of a hitch. It's a bit annoying that it closes down rather than resetting to a previous line, but that's a hurdle I'll jump over when I get to it.
I had a look around, and to be honest, whilst a few of the things may well work, I'm admittedly relatively clueless and some of the programmer speak kinda flies over my head.
It's probably because I'm being thrown into it and I'm not used to it yet, but as it stands, I need your help.
My code simply works as follows (simplified to save time):
int main()
{
int points, wager;
points = 10;
output "HEADS OR TAILS?";
if (player has 1 point or more)
{
output "Input wager";
input wager value;
output "Wager is (player input)";
output "Heads or Tails?";
input h or t; //This was what I wanted
if (player selects 'heads') //For sake of simplicity, the code
{ //here will account for both heads
int heads; //and tails.
srand(NULL);
heads = random number 1 and 2;
if (heads = 1)
{
output "HEADS!";
output "You win 'wager'!";
points = points + wager;
}
if (heads = 2)
{
output "TAILS!";
output "You lose 'wager'!";
points = points - wager;
}
}
}
if (player has 0 points)
{
output "GAME OVER";
}
}
What I want to do is have the user input either an 'h' or a 't' to determine whether or not they want heads or tails.
In your programming class, they will have told you what they expect you to use as tools for input and output, eg char inputChar; cin >> inputChar; or similar. Use whatever they told you to use in the style they want you to use, eg
cout << HEADS_OR_TAILS_PROMPT;
char inputChar;
cin >> inputChar;
switch(inputChar) {
case 'h':
{
... // code for the heads case
break;
}
case 't':
{
... // code for the tails case
break;
}
default:
// whatever you want to do if they didn't input a valid option
}
Although, to be honest, asking your professor is going to get you a better answer for what the grader is expecting than asking us is.

How do I add a "play again" feature to my C++ guessing game? Loop trouble

So for this assignment I have to include a play again function. Meaning once the person has guessed correctly the program should give the user the choice to play again or not. Also, I am trying to include a function where if the user guesses correctly in 5 guesses or less, then the program should print "Good Job!" and if it takes them more than 5 guesses, it should display "You can do better than that!". Help me please! I am a beginner in programming and I keep getting stuck in trying to fix this problem.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void )
{
int i, n = 0, r;
int answer;
srand( time( NULL ) );
r = rand() %100 +1;
char userName[15];
printf("Welcome to GUESS MY NUMBER!\n\nPlease type your name here: ");
scanf("%s", &userName);
printf("\n\nI am thinking of a number between 1 and 100.\n\nCan you guess what it is? ");
while(scanf("%d", &i))
{
if (n >= 9 && i != r)
{
printf("\n\nSorry, the number was %d.\n", r);
printf("You should have gotten it by now.\n");
printf("Better luck next time.\n\n");
system ("PAUSE");
break;
}
if (i > r)
{
n++;
printf("Your guess is high. You only get 10 guesses. Try again: ");
}
else if (i < r)
{
n++;
printf("Your guess is low. You only get 10 guesses. Try again: ");
}
else if (i == r)
{
printf("\n\nCongratulations %s!\nYou guessed the number within %d guesses!\nWould you like to play again? y/n?\n",userName, n+1,answer);
scanf("%d", &answer);
system ("PAUSE");
break;
}
}
return 0;
}
An easy thing to do is create a bool variable (originally set to true) which can be checked in the while statement and updated after the user has been given the option to continue or not. Then just change your breaks into continues and you should be in good shape.
Wrap the whole thing in another loop, and at the end of this outer loop, ask the user if he wants to play again. Either a while() or do-while() loop. If the user says yes, continue looping, otherwise exit the loop.
-Initialize the game
-Load any resources needed (in this case, none)
Begin looping continually
- Handle input
- Think
- Show results
End looping if exited
-Free any resources (in this case, none)
-Exit

I am getting breaking point error in this c++ program of mine,have a look. compiler visual c++ 2010 [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
error snapshot : https://rapidshare.com/files/3201989698/Capture5.JPG
code :
#include<fstream>
#include<conio.h>
#include<Windows.h>
#include<iostream>
using namespace std;
int ch_m;
HANDLE hConsole;
class budget
{
public :
float balance;
string due_name,loan_name;
int year,month;
float due_pay,loan_given;//due_pay due to be paid
budget()
{
balance=0;
month=1;
due_name="NO BODY";
loan_name="SAFE";
year=0;
balance = 0;
due_pay=0;
loan_given=0;
}
char get_data();
void show_data();
void budget_menu();
void balance_menu();
int yr()
{
return(year);
}
int mont()
{
return month;
}
};
void gotoxy(int x,int y)
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
cout.flush();
dwCursorPosition.X=x;
dwCursorPosition.Y=y;
hConsoleOutput=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition
(hConsoleOutput,dwCursorPosition);
}
char budget :: get_data()
{
char ch_b;
gotoxy(5,2);
cout<<"Enter Month :";
cin>>month;
gotoxy(5,4);
cout<<"Enter year :";
cin>>year;
gotoxy(5,6);
cout<<"Enter your balance for the current month and year in Rs :";
cin>>balance;
do
{
gotoxy(6,9);
cout<<"Continue adding records?(y/n)\n";
cin>>ch_b;
}while(tolower(ch_b)!='n'&&tolower(ch_b)!='y');
return ch_b;
}
void budget :: show_data()
{
gotoxy(5,2);
cout<<"Month :"<<month;
gotoxy(5,4);
cout<<"Year :"<<year;
gotoxy(5,6);
cout<<"Your balance for the current month and year in RS :"<<balance;
_getch();
}
void budget:: budget_menu()
{
system("cls");
gotoxy(12,5);
cout<<"---------------------------------------";
gotoxy(12,6);
cout<<"Budget Menu";
gotoxy(12,7);
cout<<"---------------------------------------";
gotoxy(12,10);
cout<<"1) Balance";
gotoxy(12,12);
cout<<"2) Loan Given";
gotoxy(12,14);
cout<<"3) Due to be paid";
gotoxy(12,16);
cout<<"4) Exit";
gotoxy(14,17);
cout<<"Enter your choice\n";
cin>>ch_m;
switch(ch_m)
{
case 1:
balance_menu();
break;
default:
system("cls");
gotoxy(15,8);
cout<<"Wrong Input!!";
}
}
void write_balance()
{
system("cls");
budget b;
ofstream f1;
f1.open("balance.dat",ios::app|ios::binary);
char ch;
do{
ch = b.get_data();
f1.write((char*)&b,sizeof(b));
}while(tolower(ch)=='y');
f1.close();
}
void read_balance() //PROBLEM AFTER ENTERING THIS FUNCTION
{
system("cls");
budget b;
ifstream f1;
f1.open("balance.dat",ios::in|ios::binary);
while(f1.read((char*)&b,sizeof(b)))
{ b.show_data();
}
system("cls");
cout<<"No More Records To Display!!";
getch();
f1.close();
}
void budget :: balance_menu()
{
int ch_bm;//balance menu choice
char coni;//continue?
system("cls");
gotoxy(12,6);
cout<<"1) Add current month and year balance";
gotoxy(12,7);
cout<<"2) Modify a balance";
gotoxy(12,8);
cout<<"3) Search a balance";
gotoxy(12,9);
cout<<"4)Delete a Record";
gotoxy(12,10);
cout<<"5) Display all records";
gotoxy(12,11);
cout<<"6) Back to previous menu";
gotoxy(12,12);
cout<<"7) Exit";
gotoxy(14,15);
cout<<"Enter your choice\n";
cin>>ch_bm;
switch(ch_bm)
{
case 1 :write_balance();
break;
case 5:
read_balance();
break;
default :
system("cls");
gotoxy(15,8);
cout<<"Wrong Input!!";
}
if(ch_bm!=6)
{
system("cls");
gotoxy(15,8);
cout<<"Continue?";
cin>>coni;
if(tolower(coni)=='y')
{
balance_menu();
}
}
getch();
}
void main()
{
system("cls");
budget b;
b.budget_menu();
_getch();
}
first go to option 1/1 to create the file and then 1/5 to read the contents where you will get breaking point error....
till now i have included only read and write option .
It has been 3 weeks.. i m stuck here
i have tried a lot of things
My code is working fine in turbo c++ but not in vc++
this code is to keep data of one's budget. function having problem is highlighted using comment.
Here's my review:
Use double not float unless smaller variable size is needed.
Assign 0.0 to floating point quantities. Append with 'F' if for
floating point.
Prefer one variable definition per line. Makes for easier development and
maintenance. The cost in build time is very negligible.
Prefer to use initialization list in constructors, such as :
balance(0.0), //...
Be consistent in your return statements. Parenthesis are not
required.
Do you need to have cursor positioning? It is a difficult issue
in Windows.
The C++ default I/O streams may not be compatibile with Windows
console positioning.
You are not storing records. The last iteration will always
overwrite the previous record.
Why do you need to return the operator's response from get_data?
Definitely get rid of the cursor positioning. It is getting in the
way of your development. Add it back in, if necessary, after your
program is working correctly and is robust.
You don't give the operator a chance to correct the selection and
try again. Not good
Prefer not to use binary I/O, especially when writing structures
and classes to files. If the class or structure layout changes or
the compiler inserts padding between fields your reading may not be
assigned correctly. Also, verify your data in the file is going to
be more difficult. I suggest using one text line per record and
each field separated by a tab, comma or other delimiter. This
allows you to import your data into other applications, such a
spreadsheet, for verification. Text is a lot easier to verify than
binary data.
Prefer to have I/O methods in your class / object. That way you
can make one easy statement like file << my_budget;
If you didn't use x,y positioning, you could declare the menu as
one constant text literal and output it (much easier and faster)
than having to display one line at a time. Easier to modify and
maintain too.
The main function returns int, always. Use return
EXIT_SUCCESS; if necessary.
In your methods, the budget variables are local and will
disappear upon return from the method. Reference the class
variable instead.
Always check for I/O errors. This could be where your issue is.
Pause the console before clearing it. Try this:
cin.ignore(100000, "\n");

Calling a class function from a Vector instead of an Array

I am currently working on a way to load a bunch of different NPCs from a file and loading it into my game. I have everything working correctly with arrays but I would like to change it to using a vector since I can change the size in case I need more NPCs than the space available in the array and so I don't just have a mostly empty array if I dont need many NPCs at the current time. Note that the following code is from a testing program, not my actual programming. I made it so I dont mess with the complete project by accident.
int main()
{
char input;
bool Running = true;
NPC Creatures[MAX_NPCS];
//InitCreatures loads the X, Y and Type from the file. I know with vectors I have to
//resize it as I go along, Which would be included in the function.
if(Creatures[MAX_NPCS].InitCreatures(Creatures) == false)
{
Creatures[MAX_NPCS].CleanUp(Creatures);
return 0;
}
while(Running == true)
{
cout << "(C)heck an NPC, (A)ttack and NPC or (E)xit the program\n";
cin >> input;
switch(input)
{
case 'C': Creatures[MAX_NPCS].Check(Creatures); break;
case 'c': Creatures[MAX_NPCS].Check(Creatures); break;
//The Check function just shows the X, Y and Type of the NPC
case 'A': Creatures[MAX_NPCS].Attack(Creatures); break;
case 'a': Creatures[MAX_NPCS].Attack(Creatures); break;
//Attack shows X, Y and type and then removes that NPC from the array.
case 'E': Running = false; break;
case 'e': Running = false; break;
default: cout << "That was not a valid input\n"; break;
}
}
Creatures[MAX_NPCS].CleanUp(Creatures);
cout << "Exiting\n";
system("PAUSE");
return 0;
}
Really the only problem I am having is getting Main to run the NPC Class functions from a vector instead of using the Array like I have now. I can easily change the other things in the functions I'm calling to accept the vector and handle it correctly.
When trying to use a vector to run the functions I was only able to call them when I had something like this:
Creatures[1].Attack(Creatures);
Of course when I call them like that the values don't return correctly and I usually get an error and Besides I don't know how many NPCs will be loaded for the current map, if Any.
Any help with this would be appreciated. I realize I am a newbie when it comes to programming, especially when it comes to Vectors. If my function code is needed I will gladly post it.
You could just create a vector and have the first element in there to be able to call the InitCreatures function (you could also overwrite the first creature later).
vector<NPC> Creatures(1);
Creatures[0].InitCreatures(Creatures);
I'm assuming that in class you have the parameter passed by reference.
bool InitCreatures(vector<NPC>& x) { ... }
But since you give creatures as a parameter to every function you have (do you need it in check or attack?) - wouldn't it be better to have a class to hold the NPC vector?