Hello All,
I am confused with some of the results I am getting from my C++
program. I want the program to display "This is a test" but instead
"This is a" is displayed. From experimentation I've found that by
commenting out Statement A or Statement B, I obtain the results I want
-- but I don't understand why it doesn't work the way I have it setup
now. I can see the strncpy() function is working as I expected but
somehow something is going wrong.
Thanks for your help in advance,
Mike
#include <iostream.h>
#include <conio.h>
class Transaction {
private:
char payee[51] ;
char amount[10] ;
public:
Transaction() ;
char* getPayee() ;
char* getAmount() ;
void setPayee ( char newPayee[] ) ;
void setAmount ( char newAmount[] ) ;
} ;
Transaction::Tr ansaction() {
payee[0] = NULL ;
amount[0] = NULL ;
}
char* Transaction::ge tPayee() { return( payee ) ; }
char* Transaction::ge tAmount() { return( amount ) ; }
void Transaction::se tPayee ( char newPayee[] ) {
cout << "strncpy returns : " << strncpy( payee, newPayee,
50 ) ;
payee[ 50 ] = '\0' ;
}
void Transaction::se tAmount ( char newAmount[] ) {
strncpy( amount, newAmount, 9 ) ;
payee[ 9 ] = '\0' ; // Statement A
}
void displayTransact ion( Transaction &object ) {
cout << "\nPayee : " << object.getPayee () ;
}
int main() {
Transaction myTransaction ;
myTransaction.s etPayee( "This is a test" ) ;
myTransaction.s etAmount( "1" ) ; // Statement B
displayTransact ion( myTransaction ) ;
return( 0 ) ;
} 3 1034
"Cyron" <md*******@yaho o.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. . Hello All,
I am confused with some of the results I am getting from my C++ program. I want the program to display "This is a test" but instead "This is a" is displayed. From experimentation I've found that by commenting out Statement A or Statement B, I obtain the results I want -- but I don't understand why it doesn't work the way I have it setup now. I can see the strncpy() function is working as I expected but somehow something is going wrong.
Yes. A classic copy-paste error.
void Transaction::se tAmount ( char newAmount[] ) {
Note: the input parameter should be const: char const newAmount[]
strncpy( amount, newAmount, 9 ) ; payee[ 9 ] = '\0' ; // Statement A
Review the last line once again before reading on...
You probably meant to modify "amount", not "payee".
Note that using fixed-size arrays and magic numbers in multiple
locations (10,9,51,50 array sizes) is not a good idea.
To address the latter, you could use a function such as:
template<unsign ed arraySize>
void trunc_copy_stri ng(char const* source, char (&buf)[arraySize])
{
strncpy( buf, source, arraySize-1 );
buf[arraySize-1] = '\0';
}
The setAmount function above can then correctly and safely be
implemented as:
trunc_copy_stri ng( newAmount, amount );
Hope this helps,
Ivan
-- http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Cyron wrote: void Transaction::se tAmount ( char newAmount[] ) { strncpy( amount, newAmount, 9 ) ; payee[ 9 ] = '\0' ; // Statement A }
The problem comes from Statement A here: It should be
amount[9] = 0;
*slaps forehead*
I guess I was staring at the code way too long. I'm sorry for taking
your time to point out such a simple error. Thank you for your time
and also for the advice on magic numbers and safe array access.
Mike This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: uli |
last post by:
Hi all!
I'm posting to both newsgroups, because it's actually a C++ problem but
could be that some of you using Matlab-&-MEX-&-C++ was struggling with the
same problem.
I'm trying to rewrite some Matlab routines in C++ for reusing them
identically in Matlab and some other simulation tools. For computational
algebra I want to use the Matrix Template Library (MTL,
http://www.osl.iu.edu/research/mtl/) which is written in C++ and therefore...
|
by: Ingo Nolden |
last post by:
Hi there,
I am writing c++ for some months now. I think I know the language now, but not yet all the tricky things of stl.
For a kernel which is not using mfc I am writing a serialization. For some reasons I want to implement it on my
own.
One goal is to make it robust against version changes and corrupted files. That means, when an object cannot
be deserialized, it should be skipped. The validity of the remaining document can be verified...
|
by: Omid |
last post by:
Hi.
I have problems when I try to redirect everything that is sent to cout
to a file.
I have one piece of code that works and one that does not work.
The only difference is which headers I use.
What the code does:
* First writes "This is sent to prompt" to prompt.
|
by: Generic Usenet Account |
last post by:
What exactly is the difference between the hex manipulator and the
following statement: cout.setf(ios_base::hex)?
According to Stroustrup, Third Edition, Section 21.4.4, "once set, a
base is used until reset". For some reason, I interpreted this to
mean that "<< hex" manipulator would cause the base to be set for only
the current statement, while the cout.setf(ios_base::hex) statement
would cause the base to be set for multiple...
|
by: forums_mp |
last post by:
Come to think of it I have another question:
With respect to priority task1 is the highest, task2 is the lowest. The
snippet:
SEM_ID task1_sema = semBCreate(SEM_Q_FIFO, SEM_EMPTY);
SEM_ID task2_sema = semBCreate(SEM_Q_FIFO, SEM_EMPTY);
void compute_like_crazy()
{
| |
by: SneakyElf |
last post by:
i am very green with c++ so i get stuck on very simple things
anyway, i need to write a program that would
read data from file (containing names of tv shows and their networks)
one line at a time ( ; separates tv show and network)
sort the strings according to the network and according to the show.
and so:
//to open file -
ifstream myFile;
|
by: Ramon F Herrera |
last post by:
Newbie alert: I come from C programming, so I still have that frame of
mind, but I am trying to "Think in C++". In C this problem would be
solved using unions.
Hello:
Please consider the snippet below. I have some objects which are
derived (subclassed?, subtyped?) from simpler ones, in increasing
size. There is a linear hierarchy. I need to keep them all in some
sort of linked list (perhaps std::vector). I could have several
|
by: Mark Casternoff |
last post by:
I'm getting back into C++ after a long hiatus (they didn't have
namespaces back then).
I know this question is completely subjective, but I'd be interested in
hearing which is
the "better" style and what the pros and cons are (I'm using cout as
example, but it really
applies to any similar construct):
1) using std::cout;
|
by: sanjay |
last post by:
Hi All,
I have a doubt in understanding the output of the following program
that i executed on my system. I was using DevC++ IDE which uses minGW
based compiler.
----------------------------------------------
#include <iostream>
using namespace std;
|
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...
|
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...
| |
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,...
|
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...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |