c+++ String Conversion to Integer (atoi)

Posted by wit77 on Fri, 31 May 2019 23:16:03 +0200

c+++ String Conversion to Integer (atoi)

atoi is a library function and the header file is # include

 //Prototype: int atoi(char *str);

 //Usage, the parameter that atoi passes in is a character pointer, not a string type
 #include <stdio.h>
 #include <stdlib.h>
 int main(int argc, char *argv[])
 {
     int a;double d;
     char str[] = "1024";
     char strd[] = "3.1415";
     a = atoi(str);d =atof(strd);
     printf("%d/n",a);
     printf("%g/n",d);
     return 0;
 }

Implementation of atio
Special attention is paid to boundary conditions. Writing programs is like building walls. You have to get the boundary conditions right first.

//Determine whether a character is a special escape character such as a space, and these inputs are not explicitly entered?
isspace(int x)
{
    if(x==' '||x=='/t'||x=='/n'||x=='/f'||x=='/b'||x=='/r')
        return 1;
    else 
        return 0;
}
//Determine whether it is a number and filter out other characters such as letters, @ and other symbols?
isdigit(int x)
{
    if(x<='9'&&x>='0')         
        return 1; 
    else 
        return 0;

}

//Implementation of atoi
int atoi(const char *nptr)
{
      int c;              /* current char */
      int total;         /* current total */
      int sign;           /* if '-', then negative, otherwise positive */


      /* skip whitespace */
      while ( isspace((int)(unsigned char)*nptr) )
          ++nptr;

      //Handling Positive and Negative Symbols
      c = (int)(unsigned char)*nptr;
      sign = c;           /* save sign indication */
      if (c == '-' || c == '+')               
          c = (int)(unsigned char)*nptr++;    //Conversion begins with the next sign


      total = 0;
      /**Begin to transform**/
      while (isdigit(c)) {
          total = 10 * total + (c - '0');     /* accumulate digit */
          c = (int)(unsigned char)*nptr++;    /* get next char */
      }

      //Negative case
      if (sign == '-')
          return -total;
      else
          return total;   /* return result, negated if necessary */
}

stringstream Function of string to int in C++
Header file # include < sstream >
e.g:

string result="10000";
int n=0;
stream<<result;
stream>>n;//n equals 10000

Reuse stringstream objects

Note: If you plan to use the same stringstream object in multiple transformations, remember to use the clear() method before each transformation.
e.g.

#include <sstream>
#include <iostream>
int main()
{
    std::stringstream stream;
    int first, second;
    stream<< "456"; //Insert string
    stream >> first; //Convert to int
    std::cout << first << std::endl;
    //Streams must be cleared before multiple transformations are made
    stream.clear();//Clear the error flag
    stream.str("");//Clear content "456"
    stream << true; //Insert bool value
    stream >> second; //Extract int
    std::cout << second << std::endl;
}

The greatest benefit of reusing the same stringstream (rather than creating a new object each time) object in multiple transformations is efficiency. The construction and destructor of stringstream objects are usually very CPU-consuming.

Using Templates in Type Conversion
You can easily define function templates to convert an arbitrary type to a specific target type. For example, you need to convert various numeric values, such as int, long, double, and so on, into strings, using a string type and a to_string() function with an arbitrary value t as a parameter. The to_string() function converts t to a string and writes it to result. Use str() member function to get a copy of the buffer inside the stream:

template<class T>
void to_string(string & result,const T& t)
{
   ostringstream oss;//Create a stream
   oss<<t;//Pass values in a stream
   result=oss.str();//Gets the converted character conversion and writes it to result
}
//In this way, you can easily convert multiple values into strings:
to_string(s1,10.5);//double to string
to_string(s2,123);//int to string
to_string(s3,true);//bool to string

A generic transformation template can be further defined for any type of conversion. The function template convert() contains two template parameters, out_type and in_value. The function is to convert the in_value value value into out_type:

template<class out_type,class in_value>
out_type convert(const in_value & t)
{
    stringstream stream;
    stream<<t;//Convection transfer value
    out_type result;//Store the conversion results here
    stream>>result;//Write values to result
    return result;
}
//Use convert():
double d;
string salary;
string s="12.56";
d=convert<double>(s);//d equals 12.56
salary=convert<string>(9000.0);//salary equals "9000"

Write an algorithmic transformation by yourself

long convert(char*string,long integer)  
{  
    for(int sLen=strlen(string),i=0;i<sLen;)
    integer+=(long)(string[i++]-'0')*pow(10.0,sLen-i-1);  
    return integer;  
}