How to convert a text to number?

Asked

Viewed 1,882 times

7

How should I convert a text that I know is an entire number coming externally? It would be something like a ToInt() or something like that.

2 answers

12


In C++

No header <string>, in manespace std, are defined functions that convert string for numeric types. The function name is an abbreviation of sTring to int (stoi), sTring to float (stof), sTring to unsigned lOng (stoul), and so on, depending on the desired result:

stoi, stol, stoll : Integer conversion int, long and long long

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

stof, stod, stold : Conversion to floating point numbers float, double and 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 extra arguments

Each of these functions accepts three arguments, the second of them is a pointer to a variable of type size_t, this variable will receive the index of the first character not converted (if this information is not required, it can be passed nullptr).

The third argument is the basis of the conversion by default 10. Bases can be used between 2 and 36, inclusos. For bases larger 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);
}

Exit:

"junk" em base 36 : 926192

In C

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

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

Mistakes

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

  • std::invalid_argument if it is not possible to convert the 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 made (which makes it difficult to differentiate errors from zero)
  • errno receives the amount ERANGE if overflow occurs, and the maximum possible value is returned for the requested numeric type (positive or negative, depending on the direction of the overflow)

Other types of strings

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

wcstol, wcstoll, wcstoul, wcstoull : abbreviations of wide char sTring to : lOng, lOng lOng, unsigned lOng and unsigned lOng lOng, respectively.

  • Very good answer.

7

The function strtol() is what you are looking for. There is still 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).

Don’t forget that if the data is invalid it will fail, then check if the action was successful. Unfortunately it has a bad way of return error codes, which made some people who only accompany cake recipe consider that error codes are bad (they are bad if misused and used in situations where there is a better mechanism).

You can choose the binary calculation base, 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));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.