- Реализация преобразования string to int на C/C++
- Функция преобразования string to int на C/C++
- Функция преобразования char* to int на C/C++
- Заключение
- std:: stoi, std:: stol, std:: stoll
- Contents
- [edit] Parameters
- [edit] Return value
- [edit] Exceptions
- [edit] Example
- std:: stoul
- Parameters
- Return Value
- Example
- Complexity
- Data races
- Exceptions
- See also
- String to unsigned int cpp
Реализация преобразования string to int на C/C++
Доброго времени суток! Такие функции, как stoi, atoi, atol, soul, stof, to_string и некоторые другие появились в стандарте C++11 и уже стали привычными. Особенно для пользователей Visual Studio версии 13 года и старше. Но бывают исключительные случаи, когда под рукой нет такого крутого инструмента, а только блокнот и старенький gcc. Либо инструмент есть, но он упорно отказывается работать с C++11.
Именно с такой проблемой я недавно столкнулся. Мне позарез нужно было конвертировать строку в целое число, а мой Eclipse даже через 2 часа шаманствования с бубном так и не стал дружить с функцией stoi. Было принято волевое решение написать свою реализацию преобразования string to int. Я остановился на реализации преобразования целых десятичных положительных и отрицательных чисел, этого вполне хватило.
Функция преобразования string to int на C/C++
Преобразование контейнера string в целое число int задача не самая сложная, особенно учитывая, что я работал только с десятичной системой счисления. Алгоритм простой, бежим по строке, если находим не цифру, ругаемся и возвращаем ноль, остальные цифры умножаем на десятку в нужном порядке и прибавляем к результату. Кроме того, смотрим на первый символ, если там стоит минус, не забываем это учесть.
int my_stoi(string str) < int num = 0; int ten; bool signFlag = true; //true: +, false: - for(unsigned int i = 0; i < str.length(); i++) < if(str[i] < '0' || str[i] >'9') < if(i == 0 && str[i] == '-') < signFlag = false; continue; >if(i == 0 && str[i] == '+') < signFlag = true; continue; >return NULL; > ten = 1; for(unsigned int j = 0; j < str.length() - 1 - i; j++) < ten *= 10; >num += ten * (str[i] - '0'); > if(signFlag) < return num; >else < return -num; >>
Функция преобразования char* to int на C/C++
Преобразование сишной строки в число отличается только тем, что нам самим придется посчитать длину этой строки. Вот вам, кстати, заодно и реализация strlen.
int my_stoi(char* str) < unsigned int strLen = 0; unsigned int i = 0; while(str[i] != '\0') < strLen += 1; i++; >int num = 0; int ten; bool signFlag = true; //true: +, false: - for(i = 0; i < strLen; i++) < if(str[i] < '0' || str[i] >'9') < if(i == 0 && str[i] == '-') < signFlag = false; continue; >if(i == 0 && str[i] == '+') < signFlag = true; continue; >return NULL; > ten = 1; for(unsigned int j = 0; j < strLen - 1 - i; j++) < ten *= 10; >num += ten * (str[i] - '0'); > if(signFlag) < return num; >else < return -num; >>
Заключение
А суть статьи в том, чтобы я в следующий раз не тратил 20 минут на написание stoi, а пришел сюда и скопировал код. Кроме того, возможно кому нибудь пригодится эта реализация для учебных целей, всякое может быть.
std:: stoi, std:: stol, std:: stoll
Interprets a signed integer value in the string str .
Let ptr be an internal (to the conversion functions) pointer of type char * (1,3,5) or wchar_t * (2,4,6) , accordingly.
Discards any whitespace characters (as identified by calling std::isspace) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n= base ) integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
- (optional) plus or minus sign
- (optional) prefix ( 0 ) indicating octal base (applies only when the base is 8 or 0 )
- (optional) prefix ( 0x or 0X ) indicating hexadecimal base (applies only when the base is 16 or 0 )
- a sequence of digits
The set of valid values for base is . The set of valid digits for base- 2 integers is , for base- 3 integers is , and so on. For bases larger than 10 , valid digits include alphabetic characters, starting from Aa for base- 11 integer, to Zz for base- 36 integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C locale.
If the value of base is 0 , the numeric base is auto-detected: if the prefix is 0 , the base is octal, if the prefix is 0x or 0X , the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by unary minus in the result type.
If pos is not a null pointer, then the pointer ptr will receive an address of the first unconverted character in str. c_str ( ) , and the index of that character will be calculated and stored in * pos , giving the number of characters that were processed by the conversion.
Contents
[edit] Parameters
str | — | the string to convert |
pos | — | address of an integer to store the number of characters processed |
base | — | the number base |
[edit] Return value
Integer value corresponding to the content of str.
[edit] Exceptions
- std::invalid_argument if no conversion could be performed.
- std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function ( std::strtol or std::strtoll ) sets errno to ERANGE .
[edit] Example
#include #include #include #include #include int main() { const auto data = { "45", "+45", " -45", "3.14159", "31337 with words", "words and 2", "12345678901", }; for (const std::string s : data) { std::size_t pos{}; try { std::cout "std::stoi('" s "'): "; const int i{std::stoi(s, &pos)}; std::cout i "; pos: " pos '\n'; } catch (std::invalid_argument const& ex) { std::cout "std::invalid_argument::what(): " ex.what() '\n'; } catch (std::out_of_range const& ex) { std::cout "std::out_of_range::what(): " ex.what() '\n'; const long long ll{std::stoll(s, &pos)}; std::cout "std::stoll('" s "'): " ll "; pos: " pos '\n'; } } std::cout "\nCalling with different radixes:\n"; for (const auto& [s, base] : { std::pairconst char*, int> {"11", 2}, {"22", 3}, {"33", 4}, {"77", 8}, {"99", 10}, {"FF", 16}, {"jJ", 20}, {"Zz", 36}, }) { const int i{std::stoi(s, nullptr, base)}; std::cout "std::stoi('" s "', " base "): " i '\n'; } }
std::stoi('45'): 45; pos: 2 std::stoi('+45'): 45; pos: 3 std::stoi(' -45'): -45; pos: 4 std::stoi('3.14159'): 3; pos: 1 std::stoi('31337 with words'): 31337; pos: 5 std::stoi('words and 2'): std::invalid_argument::what(): stoi std::stoi('12345678901'): std::out_of_range::what(): stoi std::stoll('12345678901'): 12345678901; pos: 11 Calling with different radixes: std::stoi('11', 2): 3 std::stoi('22', 3): 8 std::stoi('33', 4): 15 std::stoi('77', 8): 63 std::stoi('99', 10): 99 std::stoi('FF', 16): 255 std::stoi('jJ', 20): 399 std::stoi('Zz', 36): 1295
std:: stoul
Parses str interpreting its content as an integral number of the specified base, which is returned as an unsigned long value.
If idx is not a null pointer, the function also sets the value of idx to the position of the first character in str after the number.
The function uses strtoul (or wcstoul) to perform the conversion (see strtol for more details on the process).
Parameters
str String object with the representation of an integral number. idx Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used. base Numerical base (radix) that determines the valid characters and their interpretation.
If this is 0, the base used is determined by the format in the sequence (see strtol for details). Notice that by default this argument is 10, not 0.
Return Value
Example
// stoul example // std::cin, std::cout // std::string, std::stoul, std::getline int main () < std::string str; std::cout "Enter an unsigned number: "; std::getline (std::cin,str); unsigned long ul = std::stoul (str,nullptr,0); std::cout "You entered: " << ul '\n'; return 0; >
Complexity
Data races
Exceptions
If no conversion could be performed, an invalid_argument exception is thrown.
If the value read is out of the range of representable values by an unsigned long, an out_of_range exception is thrown.
An invalid idx causes undefined behavior.
See also
stoi Convert string to integer (function template) stol Convert string to long int (function template) stoull Convert string to unsigned long long (function template) strtoul Convert string to unsigned long integer (function)
String to unsigned int cpp
I´m searching a way to convert C++ string to unsigned long format.
using namespace std; int main() < string long value; // How to assign the variable "0x3F" to variable value? From string to unsigned long. // Conversion here from ID to value, but how? cout // Here the "value" would be 63 in decimal number. (0x3F)
I´ve seen many tutorials, also from cplusplus.com but they are always talking like:
unsigned long int strtoul ( const char * str, char ** endptr, int base );
But the first parameter is char* ? Not string ? Or have I understood something wrong?
To convert a std::string to a c-string (char*), use c_str().
I have no idea about the char** as the 2nd argument. The example here uses NULL, so I guess I would use NULL too 🙂
int base would be the base of your string, so for your code this would be 16. The 0x is optional if the base is 16. I guess I would recommend removing an «0x» before calling this function.
Edit: Okay, looks like the second argument would be for if you have a c_string array, which would take a little work to make from a std:string array.
they are always talking like: unsigned long int strtoul ( const char * str, char ** endptr, int base ); But the first parameter is char* ? Not string ? |
If your compiler is recent, you can use stoul(), which takes a string as the first parameter