Thread: Converting ascii to integer without using atoi

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    4

    Converting ascii to integer without using atoi

    very simple question, but I'm having a problem doing this. I simply need to take a string, "342" and instead of its ascii range, I need to change it to an integer of 342.

    I think I need to take its ascii value and subtract that from the ascii value of 0. This is what I have so far:

    Code:
    int count1
    int pos
    char string
    
    count1 = 0
    pos = 0
    cin >> string
    for (pos != '\0', pos++)
           string[pos] = count1
    	count1 = count1*10 + (pos - '0');
    I remember our teacher going over this, but I can't get ahold of him right now. This is the best I can remember, and I KNOW its wrong. I appreciate the help.

  2. #2
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    http://cboard.cprogramming.com/showthread.php?t=63595

    Ironically, the solution is similar to the one I posted here (think division and modulus).

  3. #3
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    I just worked out a quick solution. I'll say this: to convert an ASCII char to it's corresponding int take away 48. Also a digit's value depends on its place in the whole number, each place being 10 times as significant as the last.

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Your "string" variable is a char value and therefore only holds a single character. Assuming you can fix that, you are very close:

    Code:
    for ( ; str[pos] != '\0'; pos++)
        count1 = count1*10 + (str[pos] - '0');
    Or... you could always use a stringstream:

    Code:
    #include <sstream>
    #include <iostream>
    
    int main()
    {
        std::stringstream sstr("342");
        int value;
    
        sstr >> value;
    
        std::cout << value << std::endl;
    
        return 0;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Registered User
    Join Date
    Mar 2005
    Posts
    4
    Quote Originally Posted by hk_mp5kpdw
    Your "string" variable is a char value and therefore only holds a single character. Assuming you can fix that, you are very close:

    Code:
    for ( ; str[pos] != '\0'; pos++)
        count1 = count1*10 + (str[pos] - '0');
    Or... you could always use a stringstream:

    Code:
    #include <sstream>
    #include <iostream>
    
    int main()
    {
        std::stringstream sstr("342");
        int value;
    
        sstr >> value;
    
        std::cout << value << std::endl;
    
        return 0;
    }

    I can't use ANY preset functions. It has to all be manual.

    And Sam? Your reply makes sense, its just a riddle

    here is what I have so far:
    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream.h>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        int length;
        int pos;
        char str1[9];
        int strFull;
        length = 0;
        pos = 0;
        ifstream data ("sample.dat");
        if (! data.is_open())
           {
            cout << "Error opening file"; exit (1);
            }
        
        while (! data.eof() )
        {
         data.get(str1, 9, '\n');
         while (str1[pos]!= '\0', pos++)
              length = length +1;
    
         pos = 0;
         for (str1[pos]; str1[pos]!='\0' && pos<=length; pos++)
            strFull = strFull*10 + (str1[pos]-'0');
         
         cout << "This string is " << str1 << "and it is " << length << "characters long" << '\n';
         cout << "Press enter for the next line." << '\n';
         }
         cout << "This is the end of the file.";
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    str1 being the character array
    strFull being the integer

    And I just compiled this, but it won't read my data file. I have it in the same place the main.exe file runs, what is wrong?

    edit: I can't believe I feel happy about figuring out how to code correctly

  6. #6
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    Code:
    #define CHAR_TO_INT 48
    
    int new_atoi (char *string)
    {
    	int i;
    	int num = 0;
    	int digits = strlen (string);
    	int magnitude = 1;
    
    	for (i = (digits - 1); i >= 0; i--)
    	{
    		num += (string [i] - CHAR_TO_INT) * magnitude;
    		magnitude *= 10;
    	}
    
    	return num;
    }
    This is my solution (highlight the text if you really need to). Please don't blindly copy. Try to understand how it works.
    Last edited by samGwilliam; 03-29-2005 at 08:21 PM.

  7. #7
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    As mentioned above the inbuilt functions in C is of course the easiest way to convert asci numbers to actual integers. Such as 'atoi' etc.

    However, if you want to do the same without these functions look at the code below.

    It's fairly intuitive and uses a method similar to yours. In fact I'm using this for my 'Algebra project' to convert the coefficients of terms stored as a string to integers... but then that's another story.


    Code:
    /***********************************************************************
    
        A Program that converts a number entered as a string into an integer
         
         without using the atoi function or any special string 
    
         functions.
         
         By treenef
    
    ************************************************************************/
    
    
    
    #include <iostream>
    #include <string.h>
    #include <math.h>
    
    using namespace std;
    
    int main()
    {
        char string[81];
        cout<<"Enter a number as a string:";
        cin>>string;
        int size_of=strlen(string);
        
        
        int num;
        double actual_number=0;
        // 'pow' is the power function 10^2=100   => pow(10.0,2)
        // needs to be float needs to be 10.0 and not just 10
        // must include math.h library
        float counter= pow(10.0,(size_of-1));
         
        for (int a=0; a<size_of; a++)
        {
            //456 would be
            //4*100+5*10+6*1= 456
            //3=1000
            //2 =100
            //1 =10
            
            if (string[a]=='0')
            {
               num=0;
            }  
            if (string[a]=='1')
            {
               num=1;
            } 
            if (string[a]=='2')
            {
               num=2;
            } 
            if (string[a]=='3')
            {
               num=3;
            }  
            if (string[a]=='4')
            {
               num=4;
            }
            if (string[a]=='5')
            {
               num=5;
            } 
            if (string[a]=='6')
            {
               num=6;
            }
            if (string[a]=='7')
            {
               num=7;
            }
            if (string[a]=='8')
            {
               num=8;
            }  
            if (string[a]=='9')
            {
               num=9;
            } 
        
           actual_number = actual_number + num*counter;
           counter=counter/10.0;//decrement counter by division of 10
        
        
        }                          
              
        cout<<"The actual number as an integer is "<<actual_number<<endl;
        // You can now perform basic arithmetic operations on the 
        // variable 'actual_number' such as multiplication division etc
        // Eg. Multiply it by 2
        
         // cout<<actual_number*2<<endl;
        
        int stop;
        cin>>stop;
     
     
     
    }

  8. #8
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    I prefer my solution, personally...

  9. #9
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by sansuki
    here is what I have so far:
    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream.h>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        int length;
        int pos;
        char str1[9];
        int strFull;
        length = 0;
        pos = 0;
        ifstream data ("sample.dat");
        if (! data.is_open())
           {
            cout << "Error opening file"; exit (1);
            }
        
        while (! data.eof() )
        {
         data.get(str1, 9, '\n');
         while (str1[pos]!= '\0', pos++)
              length = length +1;
    
         pos = 0;
         for (str1[pos]; str1[pos]!='\0' && pos<=length; pos++)
            strFull = strFull*10 + (str1[pos]-'0');
         
         cout << "This string is " << str1 << "and it is " << length << "characters long" << '\n';
         cout << "Press enter for the next line." << '\n';
         }
         cout << "This is the end of the file.";
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    str1 being the character array
    strFull being the integer

    And I just compiled this, but it won't read my data file. I have it in the same place the main.exe file runs, what is wrong?

    edit: I can't believe I feel happy about figuring out how to code correctly

    1. You never initialize strFull, it should be set to 0 each time through the loop.
    2. <fstream.h> should be just <fstream>
    3. When you say "it won't read my data file" do you mean that when run the program simply spits out your error message "Error opening file"? It could depend on how you run it: either from the command line, or from within an IDE. It could also depend on the compiler/IDE you are using. In mine, MSVC++ 6, the files go in the same directory where the source files are located even though the actual EXEs get created in either a Release or Debug subfolder. From within an IDE, there may also be "working directory" settings you can check/modify.
    4. pos also needs to be reset to 0 every time through the loop (and before the length calculation loop) or there will be problems.
    5. length also needs to be reset to 0 every time through the loop.
    6. Your loop that calculates the length seem to duplicate in part the for loop that follows. It does not seem to really do much and could be eliminated or combined with the for loop. The length could be determined by the value of pos and the variable length could be eliminated.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  10. #10
    Registered User
    Join Date
    Mar 2005
    Posts
    4
    I changed that within about 15 minutes of posting it here is what I changed it to that WORKS and reads the data file.

    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream.h>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        int length;
        int pos;
        char str1[10];
        int strFull;
        int digit;
        ifstream data;
        data.open("sample.dat");
        while (! data.eof() )
        {
         data.get(str1,10);
         pos = 0;
         digit = 0;
         strFull = 0;
         while (str1[pos] != '\0')
               {
                digit = str1[pos] - 48;
                strFull = (strFull * 10) + digit;
                pos++;
                }
         
         cout << "This string is " << strFull << '\n';
         cout << "Press enter for the next line." << '\n';
         system("pause");
         }
         cout << "This is the end of the file."<< '\n';
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    When I said it wasn't reading the data file, it was because of two things:

    1) I didn't have the data file in the right place. I simply copied it to one directory higher, and apparently thats where I set the main.exe file to run.

    2) When it did read, it wasn't reading in the next line of data. Thats because I made the file in notepad, but didn't give it an end of line delimiter. I wrote it like this:

    Code:
    123456789
    765474382
    846254374
    but after I reformatted it to look like this:

    Code:
    123456789765474382846254374
    it worked perfectly.

    This is my first full program, so I am sure that there are TONS of mistakes. I even made another post where the final project file and data file are, if anyone wants to look at it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  3. Lame null append cause buffer to crash
    By cmoo in forum C Programming
    Replies: 8
    Last Post: 12-29-2008, 03:27 AM
  4. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  5. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM