How to convert a text to number?

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

Author: LINQ, 2017-02-20

2 answers

In C++

In header <string>, in manespace std, functions are defined that convert string to numeric types. The name of the functions, it is a shortened form of otring to int (stoi), string to f - loat (stof), string to unsigned {l[53]}ngos (stoul), so on and so forth, depending on the desired result is:

stoi, stol, stoll : conversion to integers int, long e long long

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

stof, stod, stold : conversion to floating point numbersfloat, double e long 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 whitespace before the first character that can be converted and ignore if there is text after the converted number (i.e. the string " -5.12tex" will be considered as "-5.12").

Change of basis and arguments extras

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

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

#include <iostream>
#include <string>

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

Output:

"junk" em base 36 : 926192

In C

In C, which has no specific type for strings, chars arrays can be converted to integers by the functions strtol and strtoll, of similar operation, but which receive a pointer char* as the first argument ( Maniero has better elaborated the answer for C).

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

Errors

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

  • std::invalid_argument if it is not possible to convert to string
  • std::out_of_range If conversion is possible, but the resulting number does not fit in the desired format (overflow).

In C, the errors are as follows:

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

Other string types

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

wcstol, wcstoll, wcstoul, wcstoull : abbreviations w - ide charmonised otring to : {l[53]}ngos, {l[53]}ngos {l[53]}, ngo {[52] in}unsigned {l[53]}ngos, and {[52] in}unsigned {l[53]}ngos {l[53]}, ngo, respectively.

 12
Author: Kahler, 2020-06-11 14:45:34

The function strtol() that's what you're 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 possible (check before).

Do not forget that if the data is invalid it will fail, so make sure the action was successful. Unfortunately it has a lousy way of returning error codes , which has made some people who only follow cake recipe consider that error codes are bad (they are bad if misused and used in situations that there is a better mechanism).

Allows you to choose the basis of binary, decimal, hexadecimal calculation, 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 working on ideone. E no repl.it. also I put on GitHub for future reference .

 7
Author: Maniero, 2020-11-26 21:57:48