View Full Version : C-problem
mikko3000
May 24, 2006, 07:34 AM
Please help me.
Program has the following definition:
char string[] = "1234";
How do I make a program which converts numbers given in a string to integer without using the "atoi" -function?
My greatest problem is how to compare a single character in a string.
For example
if (string[0]=="1") // this naturally is wrong
Thanks in advance.
Mikko, Finland
LTheobald
May 24, 2006, 09:28 AM
Maybe this (rather nice looking) site will help. I've not touched C so this site will be more help than me :P
Eddie's Basic Guide To C Programming (http://irc.essex.ac.uk/www.iota-six.co.uk/c/)
In particular:
C - atoi, itoa, sprintf and sscanf (http://irc.essex.ac.uk/www.iota-six.co.uk/c/g3_atoi_itoa_sprintf_sscanf.asp)
C - Copying Strings: strcpy, strncpy and strcmp - Using strcpy to Copy Strings, Using strncpy to Copy Strings, Using strcmp to Compare Strings (http://irc.essex.ac.uk/www.iota-six.co.uk/c/g4_strcpy_strncpy_strcmp.asp)
ansahahmed
Jul 20, 2006, 02:00 AM
Please help me.
Program has the following definition:
char string[] = "1234";
How do i make a program which converts numbers given in a string to integer without using the "atoi" -function?
My greatest problem is how to compare a single character in a string.
For example
if (string[0]=="1") // this naturally is wrong
Thanks in advance.
Mikko, Finland
hi mikko,
In C we can't compare two strings using relational operators.But using strcmp() we can compare two strings. Instead of using if (string[0]=="1") you just use if(string[0]='1') to compate two chracters.you can convert a character in to number by subtracting character 'zero' or integer 48.
for(I=0;string[i]!='\0';i++)
{
int j=string[i]-'0';
num=num*10+j;
}
ansahahmed
Jul 20, 2006, 02:02 AM
hi mikko,
In C we can't compare two strings using relational operators.But using strcmp() we can compare two strings. Instead of using if (string[0]=="1") you just use if(string[0]='1') to compate two chracters.you can convert a character in to number by subtracting character 'zero' or integer 48.
for(I=0;string[i]!='\0';i++)
{
int j=string[i]-'0';
num=num*10+j;
}
sarjeet
Jul 16, 2008, 03:50 AM
Hhhhhhhhhhhhhh