473,656 Members | 2,921 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 6011
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
3513
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
7555
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
2122
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
2602
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
2235
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
3513
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
5258
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
9359
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
8382
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
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
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
8600
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5629
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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
1600
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.