Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   C (https://www.askmehelpdesk.com/forumdisplay.php?f=438)
-   -   C-problem (https://www.askmehelpdesk.com/showthread.php?t=26556)

  • May 24, 2006, 07:34 AM
    mikko3000
    C-problem
    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
  • May 24, 2006, 09:28 AM
    LTheobald
    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

    In particular:
    C - atoi, itoa, sprintf and sscanf
    C - Copying Strings: strcpy, strncpy and strcmp - Using strcpy to Copy Strings, Using strncpy to Copy Strings, Using strcmp to Compare Strings
  • Jul 20, 2006, 02:00 AM
    ansahahmed
    Quote:

    Originally Posted by mikko3000
    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;

    }
  • Jul 20, 2006, 02:02 AM
    ansahahmed
    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;

    }
  • Jul 16, 2008, 03:50 AM
    sarjeet
    Hhhhhhhhhhhhhh

  • All times are GMT -7. The time now is 10:27 PM.