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<iostre am>
#include"testSt ring.h"
int main(int argc, char* argv[]) {
char* c2 = new char[];
testString::int ToStr(c2, -254);
cout << c2 << endl;
delete c2;
c2 = NULL;
return 0;*/
}
void testString::int ToStr(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::rev erseString(tmp) ; /*reverseString works - there is no
bug in that code*/
while(*str++ = *tmp++);
delete tmp;
tmp = NULL;
}
Thanks 13 1521
Ivar wrote: testString::rev erseString(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.)
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<iostre am> #include"testSt ring.h"
int main(int argc, char* argv[]) { char* c2 = new char[];
Illegal, you must specify an array size here.
testString::int ToStr(c2, -254); cout << c2 << endl; delete c2;
Illegal. This should be
delete[] c2;
c2 = NULL; return 0;*/
Remove that */
}
void testString::int ToStr(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::rev erseString(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::istringstr eam instead:
# include <sstream>
int main()
{
int i = 0;
std::istringstr eam iss("-254");
iss >> i;
}
Thanks
Jonathan
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
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
tmp[i] = (char)(y%10)+ '0'; ?
"Ivar" <ra**********@g mail.com> wrote in message
news:11******** *************@o 13g2000cwo.goog legroups.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<iostre am> #include"testSt ring.h"
int main(int argc, char* argv[]) { char* c2 = new char[]; testString::int ToStr(c2, -254); cout << c2 << endl; delete c2; c2 = NULL; return 0;*/ }
void testString::int ToStr(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::rev erseString(tmp) ; /*reverseString works - there is no bug in that code*/ while(*str++ = *tmp++); delete tmp; tmp = NULL; }
Thanks
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
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<iostre am> #include"testSt ring.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::int ToStr(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::int ToStr(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::rev erseString(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
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 program to figure out what was wrong
in my main program. This program works fine. It compiles AND the
values are correct in the output.
|
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;
|
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 then remove certain
stopwords(like and, a, an, by, the etc) which is there in another txt
file.
Then, i need to run it thru a stemmer(a program which converts words
like running to run, ie, converts them to roots words).
|
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. It is
almost like it is trying to implement it's own COM interfaces...
below is the header, and a link to the dll+code:
Zip file with header, example, and DLL:...
|
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 question..
The code fails with the error that:
"Additional information: COM object that has been separated from its
underlying RCW can not be used." if I make a call to pc.Count before
iterating though the objects.
Dim d As New...
| |
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 bCharValue As Byte, iCounter As Integer, lIndex As Long
Dim lAccValue As Long, lTableValue As Long
|
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 skills are quite basic so far, far from proficient
at this.
..htaccess file-
DirectoryIndex default.php index.asp index.html index.htm index.php
|
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 applications, namely "#RRGGBB".
function decimalColorToHTMLcolor(number) {
//converts to a integer
var intnumber = number - 0;
// isolate the colors - really not necessary
var red, green, blue;
|
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.
Furthermore, he doesn't even mark the assignments, but rather gives
tips and so forth when going over students' work. To test students'
capabilities for the purpose of state exams and qualifications though,
he actually sits down with us at a...
|
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: 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,...
| |
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...
|
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: 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: 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...
|
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
| |
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...
| |