473,386 Members | 1,694 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Please help with bug in my function - converts int to string

Hi guys - So basically I am trying to implement a function that
converts an int to a string, but it is not working for some reason -
any thoughts? My function, intToStr, is shown below. I'm just trying to
implement this to gain practice with c-style strings.

#include<iostream>
#include"testString.h"

int main(int argc, char* argv[]) {
char* c2 = new char[];
testString::intToStr(c2, -254);
cout << c2 << endl;
delete c2;
c2 = NULL;
return 0;*/
}
void testString::intToStr(char str[], int number) {
int x = number;
if(x < 0)
x = -x;
int order = 0;
while(x > 0) {
x = x/10;
order++;
}
char* tmp = new char[order+2];
tmp[0] = '\0';
int y = number;
for(int i=1; i <= order; i++) {
tmp[i] = (char)(y%10);
y = y/10;
}
if(number < 0)
tmp[order+1] = '-';
else
tmp[order+1] = '+';
testString::reverseString(tmp); /*reverseString works - there is no
bug in that code*/
while(*str++ = *tmp++);
delete tmp;
tmp = NULL;
}

Thanks

Nov 22 '05 #1
13 1509

Ivar wrote:
testString::reverseString(tmp); /*reverseString works - there is no
bug in that code*/


but there is a bug in your usage. since the first character of tmp is
null character, I suspect whether the string will be reversed (provided
reverseString doesnot do anything unusual.)

Nov 22 '05 #2
Ivar wrote:
Hi guys - So basically I am trying to implement a function that
converts an int to a string, but it is not working for some reason -
any thoughts? My function, intToStr, is shown below. I'm just trying to
implement this to gain practice with c-style strings.
Many things don't work here.
#include<iostream>
#include"testString.h"

int main(int argc, char* argv[]) {
char* c2 = new char[];
Illegal, you must specify an array size here.
testString::intToStr(c2, -254);
cout << c2 << endl;
delete c2;
Illegal. This should be

delete[] c2;
c2 = NULL;
return 0;*/
Remove that */
}
void testString::intToStr(char str[], int number) {
int x = number;
if(x < 0)
x = -x;
Use std::abs().
int order = 0;
while(x > 0) {
x = x/10;
order++;
}
char* tmp = new char[order+2];
tmp[0] = '\0';
int y = number;
Watch out! y should be absolute here or you'll get negative values!
for(int i=1; i <= order; i++) {
tmp[i] = (char)(y%10);
This should be

tmp[i] = '0' + (y%10);

if you want characters. This will only work on ASCII machines.
y = y/10;
}
if(number < 0)
tmp[order+1] = '-';
else
tmp[order+1] = '+';
testString::reverseString(tmp); /*reverseString works - there is no
bug in that code*/
while(*str++ = *tmp++);
Nooo! You just lost the pointer to the memory you allocated. Save it
*before*

char *to_delete = tmp;
delete tmp;
This should crash the application because you are not deleting from the
correct address (tmp has moved in your loop).
tmp = NULL;
}
I think there was some other errors as well, but start by fixing these.
By the way, I understand you are doing that for fun, but you should use
std::istringstream instead:

# include <sstream>

int main()
{
int i = 0;
std::istringstream iss("-254");
iss >> i;
}
Thanks

Jonathan

Nov 22 '05 #3
Jonathan Mcdougall wrote:
Ivar wrote:
char* tmp = new char[order+2];

delete tmp;


This should crash the application because you are not deleting from the
correct address (tmp has moved in your loop).


What's more, you should do

delete[] tmp;

as in main().

int *i = new int;
delete i;

int *i = new int[10];
delete[] i;
Jonathan

Nov 22 '05 #4
On 2005-11-17 04:43:01 -0500, "Jonathan Mcdougall"
<jo***************@gmail.com> said:
Ivar wrote:
for(int i=1; i <= order; i++) {
tmp[i] = (char)(y%10);


This should be

tmp[i] = '0' + (y%10);

if you want characters. This will only work on ASCII machines.


No, it will work on all machines. The characters for the digits '0'
through '9' are guaranteed to be sequential. That is, the following
will *always* produce the character '5':

putc('0' + 5, stdout);
--
Clark S. Cox, III
cl*******@gmail.com

Nov 22 '05 #5
tmp[i] = (char)(y%10)+ '0'; ?

"Ivar" <ra**********@gmail.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
Hi guys - So basically I am trying to implement a function that
converts an int to a string, but it is not working for some reason -
any thoughts? My function, intToStr, is shown below. I'm just trying to
implement this to gain practice with c-style strings.

#include<iostream>
#include"testString.h"

int main(int argc, char* argv[]) {
char* c2 = new char[];
testString::intToStr(c2, -254);
cout << c2 << endl;
delete c2;
c2 = NULL;
return 0;*/
}
void testString::intToStr(char str[], int number) {
int x = number;
if(x < 0)
x = -x;
int order = 0;
while(x > 0) {
x = x/10;
order++;
}
char* tmp = new char[order+2];
tmp[0] = '\0';
int y = number;
for(int i=1; i <= order; i++) {
tmp[i] = (char)(y%10);
// the above statement maybe need some change? tmp[i] = (char)(y%10)+ '0';
y = y/10;
}
if(number < 0)
tmp[order+1] = '-';
else
tmp[order+1] = '+';
testString::reverseString(tmp); /*reverseString works - there is no
bug in that code*/
while(*str++ = *tmp++);
delete tmp;
tmp = NULL;
}

Thanks

Nov 22 '05 #6
Clark S. Cox III wrote:
On 2005-11-17 04:43:01 -0500, "Jonathan Mcdougall"
<jo***************@gmail.com> said:
Ivar wrote:
for(int i=1; i <= order; i++) {
tmp[i] = (char)(y%10);


This should be

tmp[i] = '0' + (y%10);

if you want characters. This will only work on ASCII machines.


No, it will work on all machines. The characters for the digits '0'
through '9' are guaranteed to be sequential. That is, the following
will *always* produce the character '5':

putc('0' + 5, stdout);


Any reference? All I could find is

2.13.2.1 "[...] An ordinary character literal that contains a
single c-char has type char, with value equal to the numerical value of
the encoding of the c-char in the execution character set."
Jonathan

Nov 22 '05 #7

Ivar wrote:
Hi guys - So basically I am trying to implement a function that
converts an int to a string, but it is not working for some reason -
any thoughts? My function, intToStr, is shown below. I'm just trying to
implement this to gain practice with c-style strings.

#include<iostream>
#include"testString.h"

int main(int argc, char* argv[]) {
char* c2 = new char[];
How large an array should be allocated? Is it really necessary to make
use of the heap in this case. Why not just use:

char resultStr[100];
testString::intToStr(c2, -254);
cout << c2 << endl;
delete c2;
Bug here. Calling new[] requires you to call delete [], for example:

char* result = new char[x];
....requires...
delete []result;
c2 = NULL;
In these circumstances, this is really not necessary, as c2 is never
accessed again.
return 0;*/
}


For a function like this, I would consider providing a std::string as
argument. If not, I would explicitly indicate the result buffers size
to prevent overflow.
void testString::intToStr(char str[], int number) {
int x = number;
if(x < 0)
x = -x;
IMO the line here above will not give you the desired effect. Maybe
abs( x ) where abs gives you the absolute value of x, else try x *= -1;

int order = 0;
while(x > 0) {
x = x/10;
order++;
}
char* tmp = new char[order+2];
Why always using memory allocated on the heap?- expensive, you know...
Also, is it at all necessary to create a temporary here?
tmp[0] = '\0'; I'll assume reverseString ignores the fact that the string is
null-terminated. If this is the case, it is not string flavoured
(traditionally) at all. Null terminating your first character doesn't
make sense at all.
int y = number;
for(int i=1; i <= order; i++) {
tmp[i] = (char)(y%10);
y = y/10;
}
if(number < 0)
tmp[order+1] = '-';
else
tmp[order+1] = '+';
testString::reverseString(tmp); /*reverseString works - there is no
bug in that code*/
Yes, terminating your strings first character effectively makes it
empty :-). Reversing an empty strings gives you, well, an empty string
:-).
while(*str++ = *tmp++);
Hmmm, how about std::copy or memcpy here. Functions are there to be
used. Complex functions are made of less complex ones. Why did you not
write or own memcpy then, and use that if you want to have some
practice at doing it right;
delete tmp;
Ooops, delete []tmp; This may crash...
tmp = NULL;
Hmmm, not necessary. }

Thanks


Pleasure,

W

Nov 22 '05 #8
Jonathan Mcdougall wrote:
Clark S. Cox III wrote:
On 2005-11-17 04:43:01 -0500, "Jonathan Mcdougall"
<jo***************@gmail.com> said:
Ivar wrote:

for(int i=1; i <= order; i++) {
tmp[i] = (char)(y%10);
This should be

tmp[i] = '0' + (y%10);

if you want characters. This will only work on ASCII machines.

No, it will work on all machines. The characters for the digits '0'
through '9' are guaranteed to be sequential. That is, the following
will *always* produce the character '5':

putc('0' + 5, stdout);


Any reference? All I could find is

2.13.2.1 "[...] An ordinary character literal that contains a
single c-char has type char, with value equal to the numerical value of
the encoding of the c-char in the execution character set."
Jonathan


You are looking in the wrong place, try 2.2 character sets.

Krishanu
Nov 22 '05 #9
Krishanu Debnath wrote:
Jonathan Mcdougall wrote:
Clark S. Cox III wrote:
On 2005-11-17 04:43:01 -0500, "Jonathan Mcdougall"
<jo***************@gmail.com> said:

Ivar wrote:

> for(int i=1; i <= order; i++) {
> tmp[i] = (char)(y%10);
This should be

tmp[i] = '0' + (y%10);

if you want characters. This will only work on ASCII machines.
No, it will work on all machines. The characters for the digits '0'
through '9' are guaranteed to be sequential. That is, the following
will *always* produce the character '5':

putc('0' + 5, stdout);


Any reference? All I could find is

2.13.2.1 "[...] An ordinary character literal that contains a
single c-char has type char, with value equal to the numerical value of
the encoding of the c-char in the execution character set."


You are looking in the wrong place, try 2.2 character sets.


Well I don't have the standard (I will, someday), but there's nothing
in the draft at 2.2, except the characters accepted in a source file.
If there are more explanations in the standard, would it be possible
for someone to quote it here?

Thank you,
Jonathan

Nov 22 '05 #10
Jonathan Mcdougall wrote:
Krishanu Debnath wrote:
Jonathan Mcdougall wrote:
Clark S. Cox III wrote:
On 2005-11-17 04:43:01 -0500, "Jonathan Mcdougall"
<jo***************@gmail.com> said:

> Ivar wrote:
>
>> for(int i=1; i <= order; i++) {
>> tmp[i] = (char)(y%10);
> This should be
>
> tmp[i] = '0' + (y%10);
>
> if you want characters. This will only work on ASCII machines.
No, it will work on all machines. The characters for the digits '0'
through '9' are guaranteed to be sequential. That is, the following
will *always* produce the character '5':

putc('0' + 5, stdout);
Any reference? All I could find is

2.13.2.1 "[...] An ordinary character literal that contains a
single c-char has type char, with value equal to the numerical value of
the encoding of the c-char in the execution character set."

You are looking in the wrong place, try 2.2 character sets.


Well I don't have the standard (I will, someday), but there's nothing
in the draft at 2.2, except the characters accepted in a source file.
If there are more explanations in the standard, would it be possible
for someone to quote it here?

Thank you,
Jonathan


2.2 Character sets

para 3

"For each basic execution character set, the values of the members shall
be non-negative and distinct from one another. In both the source and
execution basic character sets, the value of each character after 0 in
the above list of decimal digits shall be one greater than the value
of the previous."

Krishanu
Nov 22 '05 #11
Ivar wrote:
Hi guys - So basically I am trying to implement a function that
converts an int to a string, but it is not working for some reason -
any thoughts? My function, intToStr, is shown below. I'm just trying to
implement this to gain practice with c-style strings.
Why? You need more practice. Char* is NOT A STRING TYPE.

Try writing this whole thing with std::string first and then once
you get your character handling debugged, you can work at converting
it to dynamically allocated chars if you must.
#include<iostream>
#include"testString.h"

int main(int argc, char* argv[]) {
char* c2 = new char[]; Not legal. Persumably you wanted new char[0], although why I don't know.
testString::intToStr(c2, -254);
cout << c2 << endl;
This is always going to print nothing (but the newline). There
is nothing testString can do to change c2 (and *c2 isn't valid).
delete c2;
Also bogus. If you allocate with new [], you must delete with delete[]:
delete [] c2;
c2 = NULL;
Unnecessary.
void testString::intToStr(char str[], int number) { int order = 0;
while(x > 0) {
x = x/10;
order++;
} x != 0 would be clearer, x is never going to be less than zero.

tmp[i] = (char)(y%10);
This almost certainly doesn't do what you want. char is just
an integral type. The unnecessary cast here does NOT convert
the value of y into a character representing that number (it
in fact does NOTHING, there is already an implicit conversion
from int to char).

The following is slighly funky buy you want:

tmp[i] = "0123456789"[y%10];
or (the following is strictly legal, but a little hokie in my
opinion):
tmp[i] = '0' + (y%10);
while(*str++ = *tmp++);
Here is where you are breaking the law. str is not big enough to
hold tmp. You are writing off the end of your allocation.
delete tmp;
tmp = NULL;


Same problem as before, use delete[]tmp and skip the unnecessary assignment.

What you probably want to do is just return tmp (without deleting it)
and assign that to a char* in your main program. Of course your main
program will now be resposible for calling delete[] on that value.
That is it should look like:

char* intToString(int);

char* rv = intToString(-254);
cout << rv << "\n";
delete [] rv;
Nov 22 '05 #12
Krishanu Debnath wrote:
Jonathan Mcdougall wrote:
Krishanu Debnath wrote:
Jonathan Mcdougall wrote:
Clark S. Cox III wrote:
> On 2005-11-17 04:43:01 -0500, "Jonathan Mcdougall"
> <jo***************@gmail.com> said:
>
>> Ivar wrote:
>>
>>> for(int i=1; i <= order; i++) {
>>> tmp[i] = (char)(y%10);
>> This should be
>>
>> tmp[i] = '0' + (y%10);
>>
>> if you want characters. This will only work on ASCII machines.
> No, it will work on all machines. The characters for the digits '0'
> through '9' are guaranteed to be sequential. That is, the following
> will *always* produce the character '5':
>
> putc('0' + 5, stdout);
Any reference? All I could find is

2.13.2.1 "[...] An ordinary character literal that contains a
single c-char has type char, with value equal to the numerical value of
the encoding of the c-char in the execution character set."

You are looking in the wrong place, try 2.2 character sets.


Well I don't have the standard (I will, someday), but there's nothing
in the draft at 2.2, except the characters accepted in a source file.
If there are more explanations in the standard, would it be possible
for someone to quote it here?

Thank you,
Jonathan


2.2 Character sets

para 3

"For each basic execution character set, the values of the members shall
be non-negative and distinct from one another. In both the source and
execution basic character sets, the value of each character after 0 in
the above list of decimal digits shall be one greater than the value
of the previous."


Ah, well, good to know. Thanks,
Jonathan

Nov 22 '05 #13

Ron Natalie wrote:

tmp[i] = "0123456789"[y%10];
Hmmm, I like...
What you probably want to do is just return tmp (without deleting it)
and assign that to a char* in your main program. Of course your main
program will now be resposible for calling delete[] on that value.
I know you probably know, but...

One would want to make it more explicit to the caller that he is
responsible for deletion of the return value. For this reason I would
not return char* in this case.

The easiest thing would be to return std::string.

Another option would be to return std::auto_ptr<std::vector<char> >. I
suppose you would know why :-). The concept of auto_array<char> also
springs to mind. The string, especially considering COW semantics are
probably the best, though.

The OP would still get the practice required (even more so).
That is it should look like:

char* intToString(int);

char* rv = intToString(-254);
cout << rv << "\n";
delete [] rv;


Now becomes:

std::string s( intToStr(24) );
std::cout << s << std::endl;

Kind regards,

Werner

Nov 22 '05 #14

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

Similar topics

20
by: da Vinci | last post by:
Hello again. I have a question regaring pass-by-reference and multiple functions. This is an assignment that I have to use pass-by-reference for everything. First off, I made the following...
10
by: Buzz | last post by:
Please convert to VB.NET protected override bool ProcessKeyEventArgs(ref Message m) { if((char)m.WParam == '.') m.WParam = (IntPtr)','; return false;
12
by: Hp | last post by:
Hi All, Thanks a lot for all your replies. My requirement is as follows: I need to read a text file, eliminate certain special characters(like ! , - = + ), and then convert it to lower case and...
0
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen....
0
by: Ewart MacLucas | last post by:
generated some WMI managed classes using the downloadable extensions for vs2003 from mircrosoft downloads; wrote some test code to enumerate the physicall processors and it works a treat, but a...
5
by: jamie | last post by:
I'm having a hell of a time figure out how to translate this piece of code. Public Function AdDDNc32(ByVal Item As String, ByVal Crc32 As Long) As Long 'Declare following variables Dim...
2
by: David | last post by:
Sent this to alt.php a couple of days back, but doesn't look like I'll get an answer, so trying here. I'm trying to convert a script to use friendly URLs, I've done this before, but my PHP...
0
Akatz712
by: Akatz712 | last post by:
The following function converts a decimal number representing a color stored in the way that Microsoft windows stores colors (low byte is red), and converts it to a hex string which is needed for web...
61
by: warint | last post by:
My lecturer gave us an assignment. He has a very "mature" way of teaching in that he doesn't care whether people show up, whether they do the assignments, or whether they copy other people's work....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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,...

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.