473,626 Members | 3,334 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simplify this ?

Alright, here is a simple function I coded, won't be hard understanding what
it does, and YES, I know, you will probably tell me it's awful code, I would
like to know how to write it better, maybe using stringstream ? here it is :

std::string IntToDiskSpace( int size)
{
if (size < 1024)
return IntToStr( size ) + " Bytes";
else if (size < 1048576)
return IntToStr( size / 1024) + "KB";
else if (size < 1073741824)
{
char* temp = new char[64];
sprintf( temp, "%2f", size / 1048576);
string result = temp;
result += " MB";
delete temp;
return result;
}
else
{
char* temp = new char[64];
sprintf( temp, "%2f", size / 1073741824);
string result = temp;
result += " GB";
delete temp;
return result;
}
}
Jul 22 '05 #1
29 2383
"Flzw" <fl****@wanadoo .fr> wrote in message
news:41******** **************@ news.wanadoo.fr ...
Alright, here is a simple function I coded, won't be hard understanding what it does,
No, we cannot know what it does, since it calls a function
whose definition you don't show.
and YES, I know, you will probably tell me it's awful code,
Well, it's incomplete code. It won't compile. If you want
folks to assess it, it's much better to post something compilable
if at all possible.
I would
like to know how to write it better, maybe using stringstream ? here it is

:

I suggest you tell us, in English, what you want it to do.
And yes, I'd get rid of the e.g. 'sprintf()'s as there
are safer, more robust ways to generate strings.

I'd also dump the unnecessary dynamic allocations.

-Mike

Jul 22 '05 #2
Allright, as Mike pointed out, there was not the code for another function I
made but that was irrelevant in the questions I had but yes I agree that was
not necessarily obvious, so let's reduce the code to this :

std::string IntToDiskSpace( int size)
{
if (size < 1073741824)
{
char* temp = new char[64];
sprintf( temp, "%2f", size / 1048576);
string result = temp;
result += " MB";
delete temp;
return result;
}
else
{
char* temp = new char[64];
sprintf( temp, "%2f", size / 1073741824);
string result = temp;
result += " GB";
delete temp;
return result;
}
}

I know I shouldn't use sprintf (thus the "unecessary dynamic allocations"
but I'm unsure on how to dit, I guess stringstream or stringbuf could help
there but these are quite obscure for me...
Jul 22 '05 #3
"Flzw" <fl****@wanadoo .fr> wrote...
Alright, here is a simple function I coded, won't be hard understanding
what
it does, and YES, I know, you will probably tell me it's awful code,
It's not awful. It's just full of assumptions which are not necessarily
correct, and some undefined behaviour. Just a little bit of undefined
behaviour, not a whole lot. Well, actually, more than a little bit.
Yeah, it's awful.
I would
like to know how to write it better, maybe using stringstream ? here it is
:

std::string IntToDiskSpace( int size)
{
if (size < 1024)
return IntToStr( size ) + " Bytes";
else if (size < 1048576)
return IntToStr( size / 1024) + "KB";
else if (size < 1073741824)
1073741824 is a literal that doesn't necessarily fit into an int. You might
want to consider using 'L' suffix.
{
char* temp = new char[64];
You really don't need to dynamically allocate 'temp'. Just declare the
array as automatic:

char temp[64];
sprintf( temp, "%2f", size / 1048576);
You probably wanted to print decimal points, the format you need is '%.2f'.
Second, the 'size / 1048576' has the type 'int', so if you have %f for
the format, the 'sprintf' expects a double value. So, you _need_ to supply
a double value there, otherwise its behaviour is undefined:

sprintf(temp, "%.2f", size / 1048576.);
string result = temp;
result += " MB";
delete temp;
Another bit of undefined behaviour. If you allocate using 'new[]', you
MUST free it using 'delete[]':

delete[] temp;

Of course, if you follow my advice to use a simple automatic array, you
don't need to delete at all.
return result;
}
else
{
Same notes in this block as above.
char* temp = new char[64];
sprintf( temp, "%2f", size / 1073741824);
string result = temp;
result += " GB";
delete temp;
return result;
}
}


A simplified version might begin like this

std::ostringstr eam os;
if (size < 1024)
return (os << size << " Bytes").str();
size /= 1024;
if (size < 1024)
return (os << size << " KB").str();
...

Victor
Jul 22 '05 #4
* Flzw:
Alright, here is a simple function I coded, won't be hard understanding what
it does, and YES, I know, you will probably tell me it's awful code, I would
like to know how to write it better, maybe using stringstream ? here it is :
First thing is to make it _correct_ as per current standards.

1024 bytes is not 1 KB. It's 1 KiB.

2^20 bytes is not 1 MB. It's 1 MiB.

std::string IntToDiskSpace( int size)
'int' is unlikely to be able to represent modern disk capacitites.

{
if (size < 1024)
return IntToStr( size ) + " Bytes";
else if (size < 1048576)
return IntToStr( size / 1024) + "KB";
else if (size < 1073741824)
Instead of decimal numbers, use values derived from expressions
such as

size_t const K = (1 << 10); // 1024
size_t const M = K*K;
size_t const G = K*M;
{
char* temp = new char[64];
sprintf( temp, "%2f", size / 1048576);


Oops.

Check out boost::lexical_ cast. See <url: http://www.boost.org>.

When you get things _working_ and _correct_ you can start to
worry about optimization -- until then forget optimization!

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #5
"Flzw" <fl****@wanadoo .fr> wrote...
Allright, as Mike pointed out, there was not the code for another function
I made but that was irrelevant in the questions I had but yes I agree that
was not necessarily obvious, so let's reduce the code to this :

std::string IntToDiskSpace( int size)
{
if (size < 1073741824)
Another advice (in addition to my post): typos are programmer's worst
enemies.
It's quite possible to make a mistake in such a constant even if you copy
and
paste it from a calculator or something. I recommend using 1024*1024*1024
instead. The compiler will calculate it for you. Besides, it's readable a
bit
better than 1034234582 (oops.. I guess I mistyped)
[...]

Jul 22 '05 #6
"Alf P. Steinbach" <al***@start.no > wrote...
* Flzw:
Alright, here is a simple function I coded, won't be hard understanding
what
it does, and YES, I know, you will probably tell me it's awful code, I
would
like to know how to write it better, maybe using stringstream ? here it
is :
First thing is to make it _correct_ as per current standards.

1024 bytes is not 1 KB. It's 1 KiB.

2^20 bytes is not 1 MB. It's 1 MiB.


And which OS do you know that reports file sizes in "KiB" or "MiB"?
Besides, isn't "MiB" a trademark or something for "Men In Black, The"?
std::string IntToDiskSpace( int size)


'int' is unlikely to be able to represent modern disk capacitites.

{
if (size < 1024)
return IntToStr( size ) + " Bytes";
else if (size < 1048576)
return IntToStr( size / 1024) + "KB";
else if (size < 1073741824)


Instead of decimal numbers, use values derived from expressions
such as

size_t const K = (1 << 10); // 1024
size_t const M = K*K;
size_t const G = K*M;
{
char* temp = new char[64];
sprintf( temp, "%2f", size / 1048576);


Oops.

Check out boost::lexical_ cast. See <url: http://www.boost.org>.


Why? Couldn't _standard_ means be used?
When you get things _working_ and _correct_ you can start to
worry about optimization -- until then forget optimization!


He didn't ask for optimization. He asked to simplify. That's mostly
related to _readability_ and _maintainabilit y_ and not optimization.

V
Jul 22 '05 #7
* Victor Bazarov:
"Alf P. Steinbach" <al***@start.no > wrote...
* Flzw:
Alright, here is a simple function I coded, won't be hard understanding
what
it does, and YES, I know, you will probably tell me it's awful code, I
would
like to know how to write it better, maybe using stringstream ? here it
is :
First thing is to make it _correct_ as per current standards.

1024 bytes is not 1 KB. It's 1 KiB.

2^20 bytes is not 1 MB. It's 1 MiB.


And which OS do you know that reports file sizes in "KiB" or "MiB"?


Some Linux utilities and desktops do, not that I know them intimately
or can provide references out of hand.

The situation for Windows is, however, as always: everything's
non-standard, including the terminology, units, etc.

For simple information about the international standard, see
<url: http://physics.nist.go v/cuu/Units/binary.html>.

Besides, isn't "MiB" a trademark or something for "Men In Black, The"?
He he he... :-)

You got me laughing.

Somebody should notify Hollywood -- great lawsuit!
Check out boost::lexical_ cast. See <url: http://www.boost.org>.


Why? Couldn't _standard_ means be used?


boost::lexical_ cast is a simple wrapper around the standard means,
namely a std::stringstre am-based conversion -- check it out... ;-)

When you get things _working_ and _correct_ you can start to
worry about optimization -- until then forget optimization!


He didn't ask for optimization. He asked to simplify. That's mostly
related to _readability_ and _maintainabilit y_


Yes. We agree! :-)
and not optimization.


Nope. All the code's ugliness stems from misguided attempts at
optimization, e.g. using sprintf instead of iostreams. Where the
possible benefit is more than cancelled by the overhead of 'new'.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #8

It's not awful. It's just full of assumptions which are not necessarily
correct, and some undefined behaviour. Just a little bit of undefined
behaviour, not a whole lot. Well, actually, more than a little bit.
Yeah, it's awful.

Thought so ;)

1073741824 is a literal that doesn't necessarily fit into an int. You
might
want to consider using 'L' suffix.
Well, it's only formy own use on a personal project compiled with a compiler
with 32bits ints, so it does fit in, I did this on purpose, but I changed
anyway, dividing by 1024 each time will probably be faster.
You really don't need to dynamically allocate 'temp'. Just declare the
array as automatic:

char temp[64];

good point, like the 2 others, we'll blame the delete[] stuff on fatigue

A simplified version might begin like this

std::ostringstr eam os;
if (size < 1024)
return (os << size << " Bytes").str();
size /= 1024;
if (size < 1024)
return (os << size << " KB").str();
...


Allrigth this is it, I tried something like this :
string IntToDiskSpace( int size)
{
std::ostringstr eam os;
double fsize = size;

if (fsize < 1024.0)
return (os << size << " Bytes").str();
fsize /= 1024.0;
if (fsize < 1024.0)
return (os << size / 1024 << " KB").str();
fsize /= 1024.0;
if (fsize < 1024.0)
return (os << ios::fixed() << setprecision(2) << fsize << " MB").str();
fsize /= 1024.0;
return (os << fixed << setprecision(2) << fsize << " GB").str();
}

There are probably mistakes in this too, but the compiler gives me one on
the first line, and I don't understand it :

error C2079: 'os' uses undefined class
'std::basic_ost ringstream<_Ele m,_Traits,_Allo c>'
with
[
_Elem=char,
_Traits=std::ch ar_traits<char> ,
_Alloc=std::all ocator<char>
]

etc ...
I can't find why....
Jul 22 '05 #9
error C2079: 'os' uses undefined class
'std::basic_ost ringstream<_Ele m,_Traits,_Allo c>'
with
[
_Elem=char,
_Traits=std::ch ar_traits<char> ,
_Alloc=std::all ocator<char>
]

etc ...
I can't find why....


#include <sstream> right =)
Jul 22 '05 #10

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

Similar topics

22
1740
by: Alan | last post by:
I have many OR in the if statement, any method to simplify? if (val == 5 | val == 9 | val == 34 | val == 111 | val == 131 | .......) // .... thank you
0
1539
by: Stylus Studio | last post by:
Stylus Studio 6 XML Enterprise Edition Now Integrates with TigerLogic XDMS XQuery and Native XML Database Bedford, MA, -- Stylus Studio ( http://www.stylusstudio.com ), the industry-leading provider of XML development tools for advanced XML data integration, and Raining Data Corporation (NASDAQ: RDTA), a leading provider of reliable data management solutions, today announced a new partnership to accelerate and make easier development of...
0
2298
by: Stylus Studio | last post by:
DataDirect XQuery(TM) is the First Embeddable Component for XQuery That is Modeled after the XQuery API for Java(TM) (XQJ) BEDFORD, Mass.--Sept. 20, 2005--DataDirect Technologies (http://www.datadirect.com), the software industry leader in standards-based components for connecting applications to data and an operating unit of Progress Software Corporation, today announced the release of DataDirect XQuery(TM), the first embeddable...
8
3662
by: ben | last post by:
i have a bit of code, that works absolutely fine as is, but seems over complicated/long winded. is there anyway to shorten/simplify it? the code is below. description of it: it's like strcpy in that it copies one block of data to another block of data until the block that is being copied contains a zero/null. the difference with this code is that it's doing 4bits at a time (all the values are 4bits) and the two blocks of data may not be...
3
2844
by: Bob Bedford | last post by:
hello I'm looking for some functions or objects allowing to select-insert-update-delete from any table in a mysql database without the need to create a new query every time. Example: selectdatas(array('field1','field2','fieldn'),array('table1','tablen'),array('left join,idy','inner join, idx')) then the function build the query, execute it and then return an object with
6
1665
by: jsceballos | last post by:
Hello. I'm writing a proxy class, i.e: a class whose methods mostly delegate their functionality to other class object. Most of the methods (which are quite a lot) defined in the class would end up being: def thisIsTheMethodName(self): self._handlerClass.thisIsTheMethodName() The handler object is the same in all methods.
6
1888
by: Patrick | last post by:
Hi All, Kind of new to this. What I have below works, but I am wondering if there is a way to make it more efficient/simpler instead of having to write an if, tr, td, blah for each datatype. How would I simplify this? Any thoughts are appreciated. Thanks, Patrick
3
4138
by: tshad | last post by:
I have dataGrid that I am filling from a List Collection and need to sort it by the various columns. So I need to be able to sort the Collection and found that you have to set up your own sorting functions to make it work. I have build the following 3 sorting functions for the 3 columns and have to call each one specifically. I am trying to find a way to cut simplify the functions and calls to make this a more
1
6073
AmLegacy
by: AmLegacy | last post by:
I'm having a hard time figuring out how to simplify the fractions. Can anyone look at this code and see if you can see something I don't. //This is the fraction adding function void add_fractions (int a, int b, int c, int d, int *ansn, int *ansd) { //int e, x, y, rem, gcd; a = a*d; //numerator 1 * denominator 2 c = c*b; //numerator 2 * denominator 1 b = b*d; // denominator 1 * denominator 2 d = b; //denominator 2 = denominator 1
0
8203
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
8711
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
8642
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...
0
8512
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
5576
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
4094
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
4206
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1515
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.