473,473 Members | 1,524 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

String to integer

Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.

help please
thank you
Freaker85

Aug 25 '06 #1
13 3187

Hi Friend,

You can use library routine atoi(), for the same

Thxs,
ragi

Freaker85 wrote:
Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.

help please
thank you
Freaker85
Aug 25 '06 #2

ragi wrote:
Hi Friend,

You can use library routine atoi(), for the same

Thxs,
ragi

Freaker85 wrote:
Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.

help please
thank you
Freaker85
you can use sscanf ()

Aug 25 '06 #3
Freaker85 wrote:
Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.
The following shows how to do it. Read the documentation
on your system for sscanf.
-------------------------------------
#include <stdio.h>

int main (void)
{
int dest = 0;
char *s1[] = {
"1234", /* 1234 */
"0x61", /* 97 */
"055", /* 45 */
"-55", /* -55 */
};
int i;

for (i=0; i<sizeof s1 / sizeof s1[0]; i++) {
/* The return from sscanf tells you how many
* values were successfully read in. Since
* we are reading in only a single value
* (dest), we check that we at get a return
* of at least 1 from sscanf.
*/
if (sscanf (s1[i], "%i", &dest)<1) {
printf ("error %i\n", i);
} else {
/* We read in using %i, but print in
* base 10 (%d). If we read in %d, then
* we would not read 0x61 or 055 correctly.
*/
printf ("%i\n", dest);
}
}
return 0;
}

goose,

Aug 25 '06 #4
ragi wrote:
<fixed toppost>
Freaker85 wrote:
Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.

help please
thank you
Freaker85
Hi Friend,

You can use library routine atoi(), for the same
Welcome to clc. Please note that in the
interests of maintaining a useful group,
the posters here generaly:
a) Avoid top-posting.
b) Read the FAQ.

goose,

Aug 25 '06 #5
Freaker85 <t_********@hotmail.comwrote:
I am new at programming in C and I am searching a manner to parse a
string into an integer.
The function atoi() will work, but you'll be better off using the more
robust strtol(); atoi() provides no error checking, among other
things.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Aug 25 '06 #6

goose wrote:
>
Welcome to clc. Please note that in the
what is clc ?
interests of maintaining a useful group,
the posters here generaly:
a) Avoid top-posting.
who is doing top posting
b) Read the FAQ.
?
goose,
Aug 25 '06 #7
Freaker85 wrote:
Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.
There are a few different functions that can parse strings into integers.

atoi(s) is equivalent to (int)strtol(s, NULL, 10)
atol(s) is equivalent to strtol(s, NULL, 10)

With the exception that atoi and atol have undefined behaviour if the
integer exceeds the int or long types respectively.

strtol is preferred because it has well defined behaviour on overflow.
There is also the flexibility of the second and third parameters. The
second one can be NULL as in the examples above, or it can be a pointer
to a char* variable that receives the location at which strtol stopped
parsing. The third variable allows you to set the base for conversion (2
for binary, 8 for octal, 10 for decimal, 16 for hexadecimal, etc.). A
base of 0 makes it work like C integer literals: a leading zero
indicates octal, and a leading 0x indicates hexadecimal.

strtol("11111111", NULL, 2) == 255
strtol("377", NULL, 8) == 255
strtol("255", NULL, 10) == 255
strtol("FF", NULL, 16) == 255

strtol("255", NULL, 0) == 255
strtol("0377", NULL, 0) == 255
strtol("0xFF", NULL, 0) == 255

Another option is sscanf, but like the atoi and atol functions, it has
undefined behaviour if the integer is too big.

--
Simon.
Aug 25 '06 #8
shaanxxx wrote:
goose wrote:
>Welcome to clc. Please note that in the
what is clc ?
clc is an abbreviation for comp.lang.c, the name of this newsgroup.
>interests of maintaining a useful group,
the posters here generaly:
a) Avoid top-posting.
who is doing top posting
ragi was top posting. It means putting your reply at the top of the
post. The correct way is to put your reply after each point that you are
replying to, like you and I do.
>b) Read the FAQ.
?
The FAQ, or Frequently Asked Questions, is a document that answers
things that are frequently asked in comp.lang.c. If you do a Google
search for "c faq" you will find it.

--
Simon.
Aug 25 '06 #9
ragi wrote:
Hi Friend,
Your reply belongs under the text you are replying to, not above. After
snipping anything you are not replying to, of course. I've corrected it
this time.
Freaker85 wrote:
>Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.
You can use library routine atoi(), for the same
Bad advice. It does not allow for error checking and if the string
represents a number that is out of range literally *anything* is allowed
to happen. Far better advice would be to use strtol assigning the result
to a long, checking the range before assigning to an int if that is what
you want, and also using the second parameter to detect errors in
conversion. Even if you don't check for conversion errors at least you
get defined behaviour if the number is too large.

Search the group for the many times this has been pointed out.
--
Flash Gordon.
Aug 25 '06 #10
ragi wrote:
>
Hi Friend,
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or:
<http://www.caliburn.nl/topposting.html>


Brian (hopes that's clearer)

Aug 25 '06 #11
Freaker85 wrote:
Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.
The easier, (relatively), way is to use sscanf(). It has the advantage
that you can scan multiple fields with a single call. The disadvantage
is that you don't get a useful return value upon failure, just whether
the field was converted and stored or not.

The more robust way is to use on of the many strtoXXXX functions
prototyped in <stdlib.h>. If you've to convert to integer values you
can use:
strtol() - long int
strtoul() - unsigned long int
strtoll() - long long int (C99 only)
strtoull() - unsigned long long int (C99 only)
strtoimax() - intmax_t (C99 only)
strtoumax() - uintmax_t (C99 only)

If the converted value should be a floating point type you can use:
strtof() - float (C99 only)
strtod() - double
strtold() - long double

These functions indicate the precise point within the string at which
conversion stopped, thus enabling you to decide whether the call was a
success or failure.

Of course, if you string is in a non-standard format, (eg. uses
regional notation, has additional characters like comma, currency
symbols etc.), then these functions will fail, when used as such. In
this case, you'll have to "tokenise" the string manually and pass a
"sanitised" version which can be converted by the strtoXXXX functions.

For details on using these functions consult a C Standard Library
reference manual. A good online source is:

<http://www.dinkumware.com/manuals/>

Aug 25 '06 #12
santosh wrote:
Freaker85 wrote:
>>
I am new at programming in C and I am searching a manner to parse
a string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.

The easier, (relatively), way is to use sscanf(). It has the
advantage that you can scan multiple fields with a single call.
The disadvantage is that you don't get a useful return value
upon failure, just whether the field was converted and stored or
not.

The more robust way is to use on of the many strtoXXXX functions
prototyped in <stdlib.h>. If you've to convert to integer values
you can use:
scanf and friends generally can input data from a stream, without
requiring any advance assignment of buffers. The various strtoxx
routines require that the string first be loaded into a string,
which needs to be predeclared. This cannot handle such anomalies
as many trailing or leading zeroes, and in some cases they cannot
reliably detect all overflows. In particular, strtoul will accept
a negagive input, which is out of range (although the conversion is
specified).

I have built some routines to handle all this, at least for
integers, which I will get around to revising to handle the
complete set sooner or later. At present the code is as follows,
and there are some insecurities to do with input of negative
integers. An earlier version of the code is mounted on my site,
but this may help.

I expect I shall eventually change some names. Probably to the
stm2xx family, using similar naming conventions as does the strtoxx
family. This will avoid problems with names beginning with str.
Otherwise I would prefer the strm2xx family as a name.

/* ------------------------------------------------- *
* File txtinput.h *
* ------------------------------------------------- */

#ifndef H_txtinput_h
#define H_txtinput_h
# ifdef __cplusplus
extern "C" {
# endif

#include <stdio.h>

/* For licensing restrictions (GPL) see readme.txt in:
* <http://cbfalconer.home.att.net/download/txtio.zip>
*
* These stream input routines are written so that simple
* conditionals can be used:
*
* if (readxint(&myint, stdin)) {
* do_error_recovery; normally_abort_to_somewhere;
* }
* else {
* do_normal_things; usually_much_longer_than_bad_case;
* }
*
* They allow overflow detection, and permit other routines to
* detect the character that terminated a numerical field. No
* string storage is required, thus there is no limitation on
* the length of input fields. For example, a number entered
* with a string of 1000 leading zeroes will not annoy these.
*
* The numerical input routines *NEVER* absorb a terminating
* char (including '\n'). Thus a sequence such as:
*
* err = readxint(&myint, stdin);
* flushln(stdin);
*
* will always consume complete lines, and after execution of
* readxint a further getc (or fgetc) will return the character
* that terminated the numeric field.
*
* They are also re-entrant, subject to the limitations of file
* systems. e.g interrupting readxint(v, stdin) operation with
* a call to readxwd(wd, stdin) would not be well defined, if
* the same stdin is being used for both calls. If ungetc is
* interruptible the run-time system is broken.

* Revised 2006-01-15 so that unsigned entry overflow (readxwd)
uses the normal C modulo (UINT_MAX + 1) operation. readxwd
still rejects an initial sign as an error.
*/

/*--------------------------------------------------------------
* Skip all blanks on f. At completion getc(f) will return
* a non-blank character, which may be \n or EOF
*
* Skipblks returns the char that getc will next return, or EOF.
*/
int skipblks(FILE *f);

/*--------------------------------------------------------------
* Skip all whitespace on f, including \n, \f, \v, \r. At
* completion getc(f) will return a non-blank character, which
* may be EOF
*
* Skipblks returns the char that getc will next return, or EOF.
*/
int skipwhite(FILE *f);

/*--------------------------------------------------------------
* Read an unsigned value. Signal error for overflow or no
* valid number found. Returns 1 for error, 0 for noerror, EOF
* for EOF encountered before parsing a value.
*
* Skip all leading blanks on f. At completion getc(f) will
* return the character terminating the number, which may be \n
* or EOF among others. Barring EOF it will NOT be a digit. The
* combination of error, 0 result, and the next getc returning
* \n indicates that no numerical value was found on the line.
*
* If the user wants to skip all leading white space including
* \n, \f, \v, \r, he should first call "skipwhite(f);"
*
* Peculiarity: This specifically forbids a leading '+' or '-'.
*/
int readxwd(unsigned int *wd, FILE *f);

/*--------------------------------------------------------------
* Read a signed value. Signal error for overflow or no valid
* number found. Returns true for error, false for noerror. On
* overflow either INT_MAX or INT_MIN is returned in *val.
*
* Skip all leading blanks on f. At completion getc(f) will
* return the character terminating the number, which may be \n
* or EOF among others. Barring EOF it will NOT be a digit. The
* combination of error, 0 result, and the next getc returning
* \n indicates that no numerical value was found on the line.
*
* If the user wants to skip all leading white space including
* \n, \f, \v, \r, he should first call "skipwhite(f);"
*
* Peculiarity: an isolated leading '+' or '-' NOT immediately
* followed by a digit will return error and a value of 0, when
* the next getc will return that following non-digit. This is
* caused by the single level ungetc available.
*/
int readxint(int *val, FILE *f);

/*--------------------------------------------------------------
* Flush input through an end-of-line marker inclusive.
*/
void flushln(FILE *f);

# ifdef __cplusplus
}
# endif
#endif
/* End of txtinput.h */

/* ------------------------------------------------- *
* File txtinput.c *
* ------------------------------------------------- */

#include <limits.h /* xxxx_MAX, xxxx_MIN */
#include <ctype.h /* isdigit, isblank, isspace */
#include <stdio.h /* FILE, getc, ungetc */
#include "txtinput.h"

/* For licensing restrictions (GPL) see readme.txt in:
* <http://cbfalconer.home.att.net/download/txtio.zip>
*
* These stream input routines are written so that simple
* conditionals can be used:
*
* if (readxint(&myint, stdin)) {
* do_error_recovery; normally_abort_to_somewhere;
* }
* else {
* do_normal_things; usually_much_longer_than_bad_case;
* }
*
* They allow overflow detection, and permit other routines to
* detect the character that terminated a numerical field. No
* string storage is required, thus there is no limitation on
* the length of input fields. For example, a number entered
* with a string of 1000 leading zeroes will not annoy these.
*
* The numerical input routines *NEVER* absorb a terminating
* char (including '\n'). Thus a sequence such as:
*
* err = readxint(&myint, stdin);
* flushln(stdin);
*
* will always consume complete lines, and after execution of
* readxint a further getc (or fgetc) will return the character
* that terminated the numeric field.
*
* They are also re-entrant, subject to the limitations of file
* systems. e.g interrupting readxint(v, stdin) operation with
* a call to readxwd(wd, stdin) would not be well defined, if
* the same stdin is being used for both calls. If ungetc is
* interruptible the run-time system is broken.
*
* Originally issued 2002-10-07
*
* Revised 2006-01-15 so that unsigned entry overflow (readxwd)
uses the normal C modulo (UINT_MAX + 1) operation. readxwd
still rejects an initial sign as an error.
*/

/* -------------------------------------------------------------
* Skip to non-blank on f, and return that char. or EOF The next
* char that getc(f) will return is unknown. Local use only.
*/
static int ignoreblks(FILE *f)
{
int ch;

do {
ch = getc(f);
} while ((' ' == ch) || ('\t' == ch));
/* while (isblank(ch)); */ /* for C99 */
return ch;
} /* ignoreblks */

/*--------------------------------------------------------------
* Skip all blanks on f. At completion getc(f) will return
* a non-blank character, which may be \n or EOF
*
* Skipblks returns the char that getc will next return, or EOF.
*/
int skipblks(FILE *f)
{
return ungetc(ignoreblks(f), f);
} /* skipblks */

/*--------------------------------------------------------------
* Skip all whitespace on f, including \n, \f, \v, \r. At
* completion getc(f) will return a non-blank character, which
* may be EOF
*
* Skipwhite returns the char that getc will next return, or EOF.
*/
int skipwhite(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (isspace(ch));
return ungetc(ch, f);
} /* skipwhite */

/*--------------------------------------------------------------
* Read an unsigned value. Signal error for overflow or no
* valid number found. Returns 1 for error, 0 for noerror, EOF
* for EOF encountered before parsing a value.
*
* Skip all leading blanks on f. At completion getc(f) will
* return the character terminating the number, which may be \n
* or EOF among others. Barring EOF it will NOT be a digit. The
* combination of error, 0 result, and the next getc returning
* \n indicates that no numerical value was found on the line.
*
* If the user wants to skip all leading white space including
* \n, \f, \v, \r, he should first call "skipwhite(f);"
*
* Peculiarity: This specifically forbids a leading '+' or '-'.
*/
int readxwd(unsigned int *wd, FILE *f)
{
unsigned int value, digit;
int status;
int ch;

#define UWARNLVL (UINT_MAX / 10U)
#define UWARNDIG (UINT_MAX - UWARNLVL * 10U)

value = 0; /* default */
status = 1; /* default error */

ch = ignoreblks(f);

if (EOF == ch) status = EOF;
else if (isdigit(ch)) status = 0; /* digit, no error */

while (isdigit(ch)) {
digit = ch - '0';
if ((value UWARNLVL) ||
((UWARNLVL == value) && (digit UWARNDIG))) {
status = 1; /* overflow */
value -= UWARNLVL;
}
value = 10 * value + digit;
ch = getc(f);
} /* while (ch is a digit) */

*wd = value;
ungetc(ch, f);
return status;
} /* readxwd */

/*--------------------------------------------------------------
* Read a signed value. Signal error for overflow or no valid
* number found. Returns true for error, false for noerror. On
* overflow either INT_MAX or INT_MIN is returned in *val.
*
* Skip all leading blanks on f. At completion getc(f) will
* return the character terminating the number, which may be \n
* or EOF among others. Barring EOF it will NOT be a digit. The
* combination of error, 0 result, and the next getc returning
* \n indicates that no numerical value was found on the line.
*
* If the user wants to skip all leading white space including
* \n, \f, \v, \r, he should first call "skipwhite(f);"
*
* Peculiarity: an isolated leading '+' or '-' NOT immediately
* followed by a digit will return error and a value of 0, when
* the next getc will return that following non-digit. This is
* caused by the single level ungetc available.
*/
int readxint(int *val, FILE *f)
{
unsigned int value;
int status, negative;
int ch;

*val = value = 0; /* default */
status = 1; /* default error */
negative = 0;

ch = ignoreblks(f);

if (EOF != ch) {
if (('+' == ch) || ('-' == ch)) {
negative = ('-' == ch);
ch = ignoreblks(f); /* absorb any sign */
}

if (isdigit(ch)) { /* digit, no error */
ungetc(ch, f);
status = readxwd(&value, f);
ch = getc(f); /* This terminated readxwd */
}

if (0 == status) { /* no readxwd overflow */
if (!negative && (value <= INT_MAX))
*val = value;
else if (negative && (value < UINT_MAX) &&
((value - 1) <= -(1 + INT_MIN)))
*val = -value;
else { /* overflow */
status = 1; /* do whatever the native system does */
if (negative) *val = -value;
else *val = value;
}
}
else if (negative) *val = -value;
else *val = value;
}
ungetc(ch, f);
return status;
} /* readxint */

/*-----------------------------------------------------
* Flush input through an end-of-line marker inclusive.
*/
void flushln(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (('\n' != ch) && (EOF != ch));
} /* flushln */

/* End of txtinput.c */

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Aug 25 '06 #13
Freaker85 wrote:
Hello,

I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.

help please
thank you
Freaker85
refer postgres code :
http://cvs.querencialivre.rs.gov.br/...root=liberdade
Try to concentrate on use of "sscanf" in formatting.c. Code is self
explainatory.
You will get a feel of open world.

Aug 26 '06 #14

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

Similar topics

9
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people...
0
by: Tom Warren | last post by:
I found a c program called similcmp on the net and converted it to vba if anybody wants it. I'll post the technical research on it if there is any call for it. It looks like it could be a useful...
35
by: Cor | last post by:
Hallo, I have promised Jay B yesterday to do some tests. The subject was a string evaluation that Jon had send in. Jay B was in doubt what was better because there was a discussion in the C#...
9
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but...
8
by: KRoy | last post by:
I have a password stored in the Registry encrypted using System.Security.Cryptography DES Algorithm. I supplied it a password and a Initialization Vector. I am trying to decrypt it using the...
5
by: jan axelson | last post by:
My application is using RegisterDeviceNotification() to detect attachment and removal of a USB HID-class device. The form is receiving WM_DEVICECHANGE messages with wParam set to...
5
by: Sakharam Phapale | last post by:
Hi All, How to declare the following statement in following structure. szPname As String * MAXPNAMELEN Public Structure MIXERCAPS public wMid As Integer public ...
12
by: Pascal | last post by:
hello and soory for my english here is the query :"how to split a string in a random way" I try my first shot in vb 2005 express and would like to split a number in several pieces in a random way...
1
by: kellysgirl | last post by:
Now what you are going to see posted here is both the set of instructions I was given..and the code I have written. The instructions I was given are as follows In this case, you will create...
2
by: =?Utf-8?B?QXNzaWRv?= | last post by:
Hello @all i need help with the following problem: Im calling an unmanaged C++ DLL (TAPI32.dll) function (lineGetCallInfo) like this: Declare Function lineGetCallInfo Lib "tapi32.dll"...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
0
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...
0
agi2029
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,...
1
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.