Thread: Converting a String of Characters to a Negative Integer

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    18

    Converting a String of Characters to a Negative Integer

    I have a function called strToInt that accepts a string of characters and converts it to an integer:

    insert
    Code:
    int strToInt (const char str[])
    {
    	int i, intValue, result = 0;
    	
    	for (i = 0; str[i] >= '0' && str[i] <= '9'; ++i)
    	{
    		intValue = str[i] - '0';
    		result = result * 10 + intValue;
    	}
    	return result;
    }
    I am trying to add to this function so that it detects a '-' as the first character in the string and converts the string to a negative number instead. How would I implement that? Thanks for any help!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Use a flag; if the first character is a '-', then set the flag; if the flag is set at the end, multiply by -1.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    18
    OK I added this code but it still doesn't seem to be working correctly:

    insert
    Code:
    int strToInt (const char str[])
    {
    	int i, intValue, result = 0;
    	int negative;
    	
    	for (i = 0; str[i] >= '0' && str[i] <= '9'; ++i)
    	{
    		if (str[0] == '-')
    		{
    			negative = 1;
    		}
    		else
    		{
    			negative = 0;
    		}
    		
    		intValue = str[i] - '0';
    		result = result * 10 + intValue;
    		
    		if (negative == 1)
    		{
    			result = result*(-1);
    		}
    		else
    		{
    			result = result;
    		}
    	}
    	return result;
    }

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Notice that if your leading character is '-', your for loop never happens. Do the check outside the for-loop; and in that case make sure your loop starts at 1 instead of 0.

  5. #5
    Registered User
    Join Date
    Apr 2008
    Posts
    18
    OK so I made these modifications:

    Code:
    int strToInt (const char str[])
    {
    	int i, intValue, result, posResult = 0;
    	int negative;
    	
    	if (str[0] == '-')
    	{
    		for (i = 1; str[i] >= '0' && str[i] <= '9'; ++i)
    		{	
    			intValue = str[i] - '0';
    			posResult = posResult * 10 + intValue;
    			result = posResult * (-1);
    		}
    	}
    	else
    	{
    		for (i = 0; str[i] >= '0' && str[i] <= '9'; ++i)
    		{	
    			intValue = str[i] - '0';
    			result = result * 10 + intValue;
    		}
    	}
    	return result;
    }
    However, now the only conversion that works correctly is the one for negative numbers. Each positive number that is returned has a 36 in front of it.

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    And you initialize result where?

  7. #7
    Registered User
    Join Date
    Apr 2008
    Posts
    18
    I use the line
    Code:
    printf("%i\n",strToInt(var1));
    where var1 is the name of the string that I am converting. The string contains the characters 5 and 8, but it is printing out 3658.

    I set result to 0 at the beginning of the function.

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by FJRRulz View Post

    I set result to 0 at the beginning of the function.
    If you did, I wouldn't have asked the question.

  9. #9
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    I set result to 0
    In your dreams? Check the code
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  10. #10
    Registered User
    Join Date
    Apr 2008
    Posts
    18
    Wow, quite the stupid mistake. Thank you good sir, it works.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Also, you can quite easily make that into one loop, instead of two loops inside if-else statement. And, you are not supposed to multiply the result by -1 every loop iteration - just once when you have collected all the digits is fine.

    The way I would do it is something like this:
    Code:
    int strToInt(char *str)
    {
        char c;
        int result = 0;
        int sign = 1;   // default to no minus. 
        // Check for minus
        if (str[0] == '-') 
        {
          str++;   // Skip over the minus.
          sign = -1;  // It's a negative number. 
        }
    
        while((c = *str))   // Stop the loop if we are at the end of the string.
        {
           // See if it's valid digit
           if (c >= '0' && c <= '9') 
           {
              result *= 10;
              result += c - '0';
           }
           else // Not a valid digit
           {
               break; // Stop looking for more digits. 
           }
           str++;  // Go to next digit. 
        }
        return result * sign;
    }
    There are probably half a dozen other variants on this function. But it's a good idea to try to avoid having two loops that do almost identical work - because sooner or later you will be fixing a bug in one side, and "miss" the bug-fix on the other variant.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. Converting a string to an integer
    By eater in forum C Programming
    Replies: 4
    Last Post: 04-26-2009, 02:39 PM
  3. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  4. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  5. Converting a string to an integer
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 08-31-2001, 10:01 PM