473,695 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a simple phonebook program,get into a loop.

i have written a simple phonebook program,i'll show you some of the
codes,the program's head file is member.h . i suppose the head file
works well.so i don't post it. here's the clips of main function
which i think has problem

// this a simple program about phonebook,it can add items,del
items,find items and
#include "member.h"
#include <fstream>
#include <vector>
#include <iostream>

using namespace std;

int DoMenu(); //display menu
void DoAdd(); //add items
void Write(); // write vector into file

string FileName;
vector <MemberphoneBoo k;

int main()
{
enum CHOICE{Exit,Add };
bool exit = false;

cout << "Enter the Name of your PhoneBook: " << endl;
cin >FileName;

while(!exit) //while exit is false,let user
input choice
{
int choice = DoMenu();

switch(choice) // do the action user select
{
case Exit:
exit = true;
break;
case Add:
DoAdd();
break;
default:
cerr << "Input error! try again!" << endl;
break;
}
}

return 0;

}

int DoMenu()
{
int choice;

cout << "Input your choice" << endl;
cout << "(0) Exit (1) Add item (2)Del item (3)Find item (4)Read
phonebook: " << endl;
cin >choice;
return choice;
}

void DoAdd() //it will add items custom input,the add it
to vector phoneBook
{ // then call write function to write vector
phoneBook into file
string OneName;
string OneAdd;
string OneNum;

cout << "Input name: ";
getline(cin,One Name);
cout << "Input address: ";
getline(cin,One Add);
cout << "Input phonenumber: ";
getline(cin,One Num);

Member newRecord(OneNa me,OneAdd,OneNu m);
phoneBook.push_ back(newRecord) ;
Write();

}

void Write()
{
ofstream fout;
fout.open (FileName.c_str (),ios::out | ios::trunc);
if (!fout.is_open ())
cerr << "Can't open file" << FileName << endl;
fout.write((cha r *)&phoneBook,si zeof(phoneBook) ); //why
can't dump &
fout.close();
}

when i select item Add,after i input name,address,ph one number. this
program will get into a loop.as below:
Input error! try again!
Input your choice
(0) Exit (1) Add item (2)Del item (3)Find item (4)Read phonebook:

those three line are filled with cmd windows.

ps. why can't i write fout.write((cha r
*)&phoneBook,si zeof(phoneBook) ); as fout.write((cha r
*)phoneBook,siz eof(phoneBook)) ;

your response is appreciated! thank you!
Aug 20 '08 #1
1 6014
On Aug 20, 8:29*am, jerry <machel2...@yah oo.cnwrote:
i have written a simple phonebook program,i'll show you some of the
codes,the program's head file is member.h . i suppose the head file
works *well.so i don't post it. *here's the clips of main function
which i think has problem

// this a simple program about phonebook,it can add items,del
items,find items and
#include "member.h"
#include <fstream>
#include <vector>
#include <iostream>

using namespace std;

int DoMenu(); * * //display menu
void DoAdd(); * * //add items
void Write(); * * // write vector into file

string FileName;
vector <MemberphoneBoo k;
Global variables. Yuck. Put these in main() and pass them into the
function (unless your teacher told you to do it this way for now, or
something).
>
int main()
{
* * * * enum CHOICE{Exit,Add };
You define this enum here but then hard code these same values into
the prompt in DoMenu() below. That's fine for a program of this size,
but you should develop good habits now for when you work on bigger
projects. In particular, make this type global so that both functions
that use it (or should use it since the one is implicitly duplicating
it) can see it.
* * * * bool exit = false;

* * * * cout << "Enter the Name of your PhoneBook: " << endl;
* * * * cin >FileName;

* * * * while(!exit) * * * * * * * * * * * *//while exit is false,let user
input *choice
* * * * {
* * * * * * * * int choice = DoMenu();

* * * * * * * * switch(choice) * * * * * * * * *// do the action user select
* * * * * * * * {
* * * * * * * * case Exit:
* * * * * * * * * * * * exit = true;
* * * * * * * * * * * * break;
* * * * * * * * case Add:
* * * * * * * * * * * * DoAdd();
* * * * * * * * * * * * break;
* * * * * * * * default:
* * * * * * * * * * * * cerr << "Input error! tryagain!" << endl;
* * * * * * * * * * * * break;
* * * * * * * * }
* * * * }

* * * * return 0;

}

int DoMenu()
{
* * * * int choice;

* * * * cout << "Input your choice" << endl;
* * * * cout << "(0) Exit (1) Add item (2)Del item (3)Find item (4)Read
phonebook: " << endl;
* * * * cin >choice;
* * * * return choice;

}

void DoAdd() * * * * * * * //it will add items custom input,the add it
to vector phoneBook
{ * * * * * * * * * * * * * * *// then callwrite function to write vector
phoneBook into file
* * * * string OneName;
* * * * string OneAdd;
* * * * string OneNum;

* * * * cout << "Input name: ";
* * * * * * * * * * * getline(cin,One Name);
* * * * cout << "Input address: ";
* * * * getline(cin,One Add);
* * * * cout << "Input phonenumber: ";
* * * * getline(cin,One Num);
You should be making sure your getline calls worked. See the FAQ
below.
>
* * * * Member newRecord(OneNa me,OneAdd,OneNu m);
* * * * phoneBook.push_ back(newRecord) ;
* * * * Write();

}

void Write()
{
*ofstream fout;
*fout.open (FileName.c_str (),ios::out | ios::trunc);
First, you can use the constructor to open the file like this:

ofstream fout( FileName.c_str( ), ios::out | ios::trunc );

Second, do you really want to truncate (i.e., erase) the file each
time you call Write()? Try ios::app or ios::ate instead. Ultimately, I
suppose you'll be reading the whole thing in at startup and writing it
out on exit, and then you would want to truncate it. In that case,
however, you don't need to specify any flags since that is the default
behavior. Hence your code would read:

ofstream fout( FileName.c_str( ) );

Much cleaner and easier to read.
*if (!fout.is_open ())
* * * * *cerr << "Can't open file" << FileName << endl;
This condition doesn't check for failed state. Use something like this
instead:

if( !fout ) { /*...*/ }

Note that you should also return or put the writing code in an else
block or something. As it stands, on failure to open the file, your
function still tries to write.
*fout.write((ch ar *)&phoneBook,si zeof(phoneBook) ); * * * * *//why
can't dump &
First of all, use the formatted output operator <<, like you do with
cout. The iostream read and write functions are for unformatted (most
often, binary) I/O, not vanilla text I/O like you're doing. Second,
you're trying to write out a vector, not the *contents* of the vector.
A vector is a container class that maintains a few things to keep
track of the actual contents, and you don't really care about saving
those housekeeping details. Try something like:

fout << phoneBook[0].name << '\n'
<< phoneBook[0].address << '\n'
<< phoneBook[0].phone << '\n';

(I guess on the member names since you didn't include the header.) You
can put this in a loop in various ways (note that I'm checking the
file's state in the for-loop's condition; this is best, but it could
be omitted for a tiny program like this):

for( size_t n=0; fout && n < phoneBook.size( ); ++n )
fout << phoneBook[ n ].name << '\n' /*...*/;

Or

typedef vector<Member>: :iterator iter;
for( iter it = phoneBook.begin (); fout && it != phoneBook.end() ; +
+it )
fout << it->name << '\n' /*...*/;

There are other snazzier ways to do it like defining a << operator for
your Member class, which would allow you to write:

fout << phoneBook[0] << '\n';

or to use std::copy and std::ostream_it erator, but that is for another
day.
*fout.close();
FWIW, the fstream will close automatically when you exit this
function, so you don't need to explicitly close it here. You might
want to explicitly close a file sometimes, but here it's optional and
just more code to write.
}

when i select item Add,after i input name,address,ph one number. this
program will get into a loop.as below:
Input error! try again!
Input your choice
(0) Exit (1) Add item (2)Del item (3)Find item (4)Read phonebook:

those three line are filled with cmd windows.
See these FAQs:

http://www.parashift.com/c++-faq-lit....html#faq-15.2
http://www.parashift.com/c++-faq-lit....html#faq-15.3
http://www.parashift.com/c++-faq-lit....html#faq-15.6
ps. why can't i write *fout.write((ch ar
*)&phoneBook,si zeof(phoneBook) ); * as *fout.write((ch ar
*)phoneBook,siz eof(phoneBook)) ;
See above.

Cheers! --M
Aug 20 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

38
3523
by: jrlen balane | last post by:
basically what the code does is transmit data to a hardware and then receive data that the hardware will transmit. import serial import string import time from struct import * ser = serial.Serial()
0
7561
by: Tal Sharfi | last post by:
Hi everyone I recently had the need for StringGrid object same as the one that Delphi has. An object that helps show lists of other objects in a simple grid. I searched the news groups and found none, so, I wrote one and decided to share it with you. It's a very simple one with few functions. I derived a DataGrid and added to it a DataTable to hold the data. The object itself is handling the synchronization between them, because...
8
2124
by: SK | last post by:
Hi I am trying to write a simple C program with devc++ as the complier using the concept of arrays. I cannot get the program to compile without mutiple errors. If anyone has the time to help me I would really apprecaite it. Thanks SK //Specs to be added later //C Libraries #include <stdio.h>
2
2605
by: QHorizon | last post by:
Hello, I'm new to Python (I've learned everything up to iterators so far) and fairly new to Programming. This would be my first real program: #Coordinate Geometry (The whole program is not shown) import math import sys print "Welcome to the Coordinate Geometry Calculator!"
4
2236
by: DDCane | last post by:
i need to make a dictionary that works as a telephone book. this is what needs to happen when i type in the following: add name number – it adds the name and number to the phonebook lookup name – returns the number for the given name alias name newname – lets u look up the number by typing the name or the alias "newname". change name number – changes the number that is connected to the given name quit – shuts down the the interactive...
30
3520
by: galiorenye | last post by:
Hi, Given this code: A** ppA = new A*; A *pA = NULL; for(int i = 0; i < 10; ++i) { pA = ppA; //do something with pA
12
5261
by: ShaneMcD | last post by:
Hi, I'm doing a fairly basic Java course, and I have to design a very simple phone book programme which will take a small number of phone entries (the number can be predefined so I can use arrays instead of lists), sort them and allow them to be searched. I'm just concentrating on the sorting part of the problem at the moment, and I'm not sure where to start! There's two ways I can approach it: 1) Create an array of objects, each object...
1
3507
by: cooolsson | last post by:
I need to create a phonebook with the help of dictionaries, classes and objects. It needs to add a user and a phone number, it needs to lookup a phone number with the help of the name, it needs to change the the name of the user that you choose but still make his old name searchable, like an alias and it needs to change the phone number of one person. The idea is that you type in a name and a phone number and then when you choose to do an alias...
5
9365
by: just curious | last post by:
Create a C++ console application that uses a while loop to count, total, and average a series of positive integers entered by a user. The user enters a –1 to signal the end of data input and to display the count, total, and average of the numbers entered. The pseudocode for the program is: Start Enter user's input Begin Loop
0
8625
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9113
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8977
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8841
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7658
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2997
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2269
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1971
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.