473,660 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

char -> int

ern
Anybody know a quick and dirty function for going from "547.645867 9" to
the integer version 548 ?

i.e.

int returnIntegerEq uivalent(char * charNum){
int intNum;
//Do some stuff...
return intNum;
}

I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks,

Nov 15 '05 #1
13 2547

ern wrote:
Anybody know a quick and dirty function for going from "547.645867 9" to
the integer version 548 ?

i.e.

#include <stdlib.h>
#include <math.h>
int returnIntegerEq uivalent(char * charNum){
int intNum;
double dNum = strtod(charNum, NULL);
if (ceil(dNum) - dNum > 0.5)
intNum = (int) floor(dNum);
else
intNum = (int) ceil(dNum);
return intNum;
}

I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks,


Nov 15 '05 #2
ern wrote:
Anybody know a quick and dirty function for going from "547.645867 9" to
the integer version 548 ?

i.e.

int returnIntegerEq uivalent(char * charNum){
int intNum;
//Do some stuff...
intNum = atof(charNum) + 0.5;
return intNum;
}

I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks,


Nov 15 '05 #3
"ern" <er*******@gmai l.com> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Anybody know a quick and dirty function for going from "547.645867 9" to
the integer version 548 ?


rounding to +infinity is done with ceil()
examples:
547.6 -> 548
547.4 -> 548
547 -> 547
-547.4 -> -547
-547.6 -> -547

rounding to -infinity is done with floor()
examples:
547.6 -> 547
547.4 -> 547
547 -> 547
-547.4 -> -548
-547.6 -> -548

truncating the fractional part is done by converting/casting to integer
type:
547.6 -> 547
547.4 -> 547
547 -> 547
-547.4 -> -547
-547.6 -> -547

rounding to the nearest integer can be achieved from truncating if 0.5 is
first [added to]/[subtracted from] the number being rounded:
547.6+0.5 -> 548
547.4+0.5 -> 547
547+0.5 -> 547
-547.4-0.5 -> -547
-547.6-0.5 -> -548

Something like that,
Alex
Nov 15 '05 #4
"ern" <er*******@gmai l.com> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Anybody know a quick and dirty function for going from "547.645867 9" to
the integer version 548 ?

i.e.

int returnIntegerEq uivalent(char * charNum){
int intNum;
//Do some stuff...
return intNum;
}

I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks,


I'm not sure how "dirty" (or quick, for that matter) it is, but you'll
probably want to look into the strtol() function:
http://ccs.ucsd.edu/c/stdlib.html#strtol. More intuitively, you could
convert the string to a (double) using the related strtod() function
(http://ccs.ucsd.edu/c/stdlib.html#strtod), and then cast the result to an
(int), especially since you have to do that anyway with strtol() unless you
declare "intNUM" of type (long).

-Charles
Nov 15 '05 #5
ern wrote:
Anybody know a quick and dirty function for going from "547.645867 9" to
the integer version 548 ?

i.e.

int returnIntegerEq uivalent(char * charNum){
int intNum;
//Do some stuff...
return intNum;
}

I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks,

#include <errno.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>

/* making no assumption that s represents an value in the range of an
int, but accepting that some initial portion is supposed to represent
a legal double value. 0 is returned (with errno set) if a problem occurs
with the string to float conversion. */

double floatingstring2 floatingint(con st char *s)
{
double x, fp, ip;
int sign = 1;
errno = 0;
x = strtod(s, 0);
if (errno)
return 0;
if (x < 0) {
sign = -1;
x = -x;
}
fp = modf(x, &ip);
if (fp >= .5)
ip++;
return sign * ip;
}

int main(void)
{
char s[] = "547.645867 9";
char t[] = "-547.6458679";
printf("The initial string (s) is \"%s\n", s);
printf("floatin gstring2floatin gint(s) returns %g\n",
floatingstring2 floatingint(s)) ;
printf("The initial string (t) is \"%s\n", t);
printf("floatin gstring2floatin gint(t) returns %g\n",
floatingstring2 floatingint(t)) ;
return 0;
}

The initial string (s) is "547.645867 9
floatingstring2 floatingint(s) returns 548
The initial string (t) is "-547.6458679
floatingstring2 floatingint(t) returns -548
Nov 15 '05 #6

"Charles M. Reinke" <cm******@ece.g atech.edu> wrote in message
news:dh******** **@news-int.gatech.edu. ..
"ern" <er*******@gmai l.com> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Anybody know a quick and dirty function for going from "547.645867 9" to
the integer version 548 ?

i.e.

int returnIntegerEq uivalent(char * charNum){
int intNum;
//Do some stuff...
return intNum;
}

I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks,

I'm not sure how "dirty" (or quick, for that matter) it is, but you'll
probably want to look into the strtol() function:
http://ccs.ucsd.edu/c/stdlib.html#strtol. More intuitively, you could
convert the string to a (double) using the related strtod() function
(http://ccs.ucsd.edu/c/stdlib.html#strtod), and then cast the result to an
(int), especially since you have to do that anyway with strtol() unless

you declare "intNUM" of type (long).

-Charles


After sending my inital response I realized that the proper solution could
be a little complicated, hence the following code:
holomask>cat h.c
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int returnIntegerEq uivalent(char *charNum) {
int intNum;
char *str_test;

intNum = floor(strtod(ch arNum, &str_test)+0.5) ;
if(charNum==str _test)
printf("Error converting string.\n");

return intNum;
} /* returnIntegerEq uivalent */

int main(void) {
int intNum;
char charNum[]="547.645867 9";

intNum = returnIntegerEq uivalent(charNu m);
printf("test string: %s\ninteger value: %d\n", charNum, intNum);

return 0;
} /* main */
holomask>gcc -Wall -ansi -pedantic -lm -o h.exe h.c
holomask>h.exe
test string: 547.6458679
integer value: 548
Nov 15 '05 #7
"Charles M. Reinke" <cm******@ece.g atech.edu> wrote in
news:dh******** **@news-int.gatech.edu:
intNum = floor(strtod(ch arNum, &str_test)+0.5) ;
if(charNum==str _test)
printf("Error converting string.\n");


In cases like this, it might be more useful to test that the string
contained nothing other than a valid number. For example, the test above
would not raise an error if

"547.64.586 79"

was passed to it.

Thus, a test like

if( *str_test ) {
/* error */
}

might be more useful in practice.

Sinan
--
A. Sinan Unur <1u**@llenroc.u de.invalid>
(reverse each component and remove .invalid for email address)
Nov 15 '05 #8

"A. Sinan Unur" <1u**@llenroc.u de.invalid> wrote in message
news:Xn******** *************** *****@127.0.0.1 ...
In cases like this, it might be more useful to test that the string
contained nothing other than a valid number. For example, the test above
would not raise an error if

"547.64.586 79"

was passed to it.
Agreed.
Thus, a test like

if( *str_test ) {
/* error */
}

might be more useful in practice.

Sinan


Point well taken. ;-)

-Charles
Nov 15 '05 #9
"Charles M. Reinke" <cm******@ece.g atech.edu> wrote in
news:dh******** **@news-int.gatech.edu:

"A. Sinan Unur" <1u**@llenroc.u de.invalid> wrote in message
news:Xn******** *************** *****@127.0.0.1 ...
In cases like this, it might be more useful to test that the string
contained nothing other than a valid number. For example, the test
above would not raise an error if

"547.64.586 79"

was passed to it.
Agreed.
Thus, a test like

if( *str_test ) {
/* error */
}

might be more useful in practice.


....

Point well taken. ;-)


I should note that this requires str_test to be initialized.

char *str_test = charNum;

should be good enough.

--
A. Sinan Unur <1u**@llenroc.u de.invalid>
(reverse each component and remove .invalid for email address)

comp.lang.perl. misc guidelines on the WWW:
http://mail.augustmail.com/~tadmc/cl...uidelines.html
Nov 15 '05 #10

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

Similar topics

9
2201
by: Christopher Benson-Manica | last post by:
I need a smart char * class, that acts like a char * in all cases, but lets you do some std::string-type stuff with it. (Please don't say to use std::string - it's not an option...). This is my attempt at it, but it seems to be lacking... I'm aware that strdup() is nonstandard (and a bad idea for C++ code) - please just bear with me: /* Assume relevant headers are included */ class char_ptr {
5
9734
by: Alex Vinokur | last post by:
"Richard Bos" <rlb@hoekstra-uitgeverij.nl> wrote in message news:4180f756.197032434@news.individual.net... to news:comp.lang.c > ben19777@hotmail.com (Ben) wrote: > > 2) Structure casted into an array of char > > typedef struct { > > char name; > > int age; > > int id; > > } person; > >
5
2531
by: Sona | last post by:
I understand the problem I'm having but am not sure how to fix it. My code passes two char* to a function which reads in some strings from a file and copies the contents into the two char*s. Now when my function returns, the values stored in the char* are some garbage values (perhaps because I didn't allocate any memory for them).. but even if I allocate memory in the function, on the return of this function I see garbage.. here is my...
2
3404
by: Peter Nilsson | last post by:
In a post regarding toupper(), Richard Heathfield once asked me to think about what the conversion of a char to unsigned char would mean, and whether it was sensible to actually do so. And pete has raised a doubt in my mind on the same issue. Either through ignorance or incompetence, I've been unable to resolve some issues. 6.4.4.4p6 states...
5
3962
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a variable **var make it an array of pointers? I realize that 'char **var' is a pointer to a pointer of type char (I hope). And I realize that with var, var is actually a memory address (or at
12
10078
by: GRoll35 | last post by:
I get 4 of those errors. in the same spot. I'll show my parent class, child class, and my driver. All that is suppose to happen is the user enters data and it uses parent/child class to display it. here is the 4 errors. c:\C++\Ch15\Employee.h(29): error C2440: '=' : cannot convert from 'char ' to 'char '
18
4045
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
4
3219
by: Paul Brettschneider | last post by:
Hello all, consider the following code: typedef char T; class test { T *data; public: void f(T, T, T); void f2(T, T, T);
16
6782
by: s0suk3 | last post by:
This code #include <stdio.h> int main(void) { int hello = {'h', 'e', 'l', 'l', 'o'}; char *p = (void *) hello; for (size_t i = 0; i < sizeof(hello); ++i) {
29
9961
by: Kenzogio | last post by:
Hi, I have a struct "allmsg" and him member : unsigned char card_number; //16 allmsg.card_number
0
8341
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,...
1
8542
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,...
0
8630
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...
1
6181
isladogs
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...
0
5650
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
4177
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...
1
2760
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
1984
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1740
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.