How to convert text to number?

6

How do I convert a text that I know is an integer coming from externally? It would be something like ToInt() or something like that.

    
asked by anonymous 20.02.2017 / 13:57

2 answers

8

In C ++

In the header <string> , in the std manespace, functions are defined that convert string to numeric types. The name of the functions is an abbreviation of tring to i nt ( stoi ), s tring < strong to u u u u u > l ong ( stof ), and so on, depending on the desired result:

stoul , stoi , stol : Conversion to integers stoll , int and long

long long , stoul : Conversion to unsigned integers stoull and unsigned long

unsigned long long , stof , stod : Conversion to floating-point numbers stold , float and double

Example :

#include <string>
#include <iostream>

int main() {
    std::string S1("3.1415");
    std::cout << "int   : " << std::stoi(S1) <<std::endl;
    std::cout << "float : " << std::stof(S1) <<std::endl;
}

These functions ignore all blanks before the first character that can be converted and ignore if there is text after the converted number (that is, the string long double will be considered as " -5.12tex" ).

Change base and extra arguments

Each of these functions accepts three arguments, the second of which is a pointer to a variable of type "-5.12" , this variable will receive the index of the first unconverted character (if this information is not required, you can pass size_t ).

The third argument is the basis of conversion, by default nullptr . Bases between 10 and 2 , inclusive, may be used. For bases larger than ten, the letters of the alphabet, in order, are considered the digits after 36 :

#include <iostream>
#include <string>

int main()
{
    std::cout << "\"junk\" em base 36 : " << std::stol("junk", nullptr, 36);
}

Output:

9

In C

In C, which has no type specific to strings, chars arrays can be converted to integers by the functions "junk" em base 36 : 926192 and strtol , of similar operation, but which receive a strtoll pointer as the first argument ( bigown has best worked out the answer for C ).

In C, the second argument is a pointer to a pointer of char char* , and instead of returning the position of the first unconverted character, the function will write its address (can be passed char** , which will be ignored if this information is not desired).

Errors

Since not every string can be transformed into a number, the functions may fail for some inputs. In C ++, two exceptions are possible:

  • NULL if the string can not be converted
  • std::invalid_argument if conversion is possible, but the resulting number does not fit in the desired format (overflow).

In C, the errors are as follows:

  • Returned zero ( std::out_of_range ) if conversion can not be done (which makes it difficult to differentiate errors from zero)
  • 0 receives the value errno if overflow occurs, and the maximum possible value is returned for the required numeric type (positive or negative, depending on the direction of the overflow)

Other types of strings

Strings that use ERANGE can be converted in the same way in C ++ (which has overload of functions for class w_chart ), or with slightly different name functions in C:

wstring , wcstol , wcstoll , wcstoul : abbreviations of w ide c har s l l ong, l ong l ong, u > nsigned l ong and u nsigned l ong     

20.02.2017 / 15:11
7

strtol() is what you are looking for. There is also atoi() which is considered obsolete. If you want a int get the long with the first function and then do the conversion if it is possible (check first).

Do not forget that if the data is invalid it will fail, so make sure the action was successful. Unfortunately you have a bad way to return error codes, which made some people who only accompany cake recipe consider Error codes are bad (they are bad if misused and used in situations where there is a better mechanism).

You can choose the basis of calculation binary, decimal, hexadecimal, etc.

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char *end;
    printf("\" 999999999999999999999999999999999999999999999\" em decimal --> %ld - ", strtol(" 999999999999999999999999999999999999999999999", &end, 10));
    printf("Erro: %s\n", strerror(errno));
    printf("\"1010\" em binário --> %ld\n", strtol("1010", NULL, 2)); //sem tratamento de erro
    printf("\"12\" em octal     --> %ld\n", strtol("12", NULL, 8));
    printf("\"A\"  em hex       --> %ld\n", strtol("A", NULL, 16));
    printf("\"junk\" em base 36 --> %ld\n", strtol("junk", NULL, 36));
    printf("\"012\" detecção    --> %ld\n", strtol("012", NULL, 0));
    printf("\"0xA\" detecção    --> %ld\n", strtol("0xA", NULL, 0));
    printf("\"junk\" detecção   -->  %ld - ", strtol("junk", &end, 0));
    printf("Erro: %s\n", strerror(errno));
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

    
20.02.2017 / 13:57