Как из string сделать int
Перейти к содержимому

Как из string сделать int

Руководство по программированию на C#. Преобразование строки в число

Для преобразования string в число используется вызов метода Parse или TryParse , который можно найти в числовых типах ( int , long , double и т. д.), или используются методы в классе System.Convert.

Немного эффективнее и проще вызвать метод TryParse (например, int.TryParse("11", out number) ) или метод Parse (например, var number = int.Parse("11") ). Использование метода Convert более удобно для общих объектов, реализующих IConvertible.

Можно использовать методы Parse или TryParse в числовом типе, который предположительно содержит строка, таком как тип System.Int32. Метод Convert.ToInt32 использует Parse внутри себя. Метод Parse возвращает преобразованное число; метод TryParse возвращает логическое значение, которое указывает, успешно ли выполнено преобразование, и возвращает преобразованное число в параметр out . Если строка имеет недопустимый формат, Parse создает исключение, а TryParse возвращает значение false . В случае сбоя операции синтаксического анализа при вызове метода Parse вы всегда должны использовать обработку исключений, чтобы перехватить FormatException.

Вызов метода Parse или TryParse

Методы Parse и TryParse игнорируют пробелы в начале и в конце строки, но все остальные символы должны быть символами, которые образуют соответствующий числовой тип ( int , long , ulong , float , decimal и т. д.). Любые пробелы в строке, образующие число, приводят к ошибке. Например, можно использовать для decimal.TryParse синтаксического анализа «10», «10,3» или «10», но этот метод нельзя использовать для синтаксического анализа 10 из «10X», «1 0» (обратите внимание на внедренное пространство), «10.3» (обратите внимание на внедренное пространство), «10e1» ( float.TryParse работает здесь) и т. д. Строку со значением null или String.Empty невозможно успешно проанализировать. Вы можете проверить наличие NULL или пустой строки, прежде чем пытаться ее проанализировать, вызвав метод String.IsNullOrEmpty.

В указанном ниже примере демонстрируются успешные и неуспешные вызовы методов Parse и TryParse .

В следующем примере показан один из подходов к анализу строки, которая, как ожидается, будет включать начальные числовые символы (включая шестнадцатеричные символы) и конечные нечисловые символы. Он назначает допустимые символы в начале новой строки перед вызовом метода TryParse. Поскольку анализируемые строки содержат небольшое количество символов, в примере вызывается метод String.Concat для назначения допустимых символов новой строке. Для большей строки можете использовать класс StringBuilder.

Вызов методов класса Convert

В следующей таблице перечислены некоторые методы класса Convert, которые можно использовать для преобразования строки в число.

How to convert a string to an int in C++

There are certain instances in C++ programming when it is necessary to convert a certain data type to another; one such conversion is from a string to an int .

Let’s have a look at a few of the ways to convert a string to an int :

1. Using the stringstream class

The stringstream class is used to perform input/output operations on string-based streams. The << and >> operators are used to extract data from( << ) and insert data into ( >> ) the stream. Take a look at the example below:​

2. Using stoi()

The stoi() function takes a string as a parameter and returns the integer representation. Take a look at the example below:

3. Using atoi()

The atoi() function is different from the stoi() function in a few ways. First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.

How can I convert a std::string to int?

I want to convert a string to an int and I don’t mean ASCII codes.

For a quick run-down, we are passed in an equation as a string. We are to break it down, format it correctly and solve the linear equations. Now, in saying that, I’m not able to convert a string to an int.

I know that the string will be in either the format (-5) or (25) etc. so it’s definitely an int. But how do we extract that from a string?

One way I was thinking is running a for/while loop through the string, check for a digit, extract all the digits after that and then look to see if there was a leading ‘-‘, if there is, multiply the int by -1.

It seems a bit over complicated for such a small problem though. Any ideas?

24 Answers 24

In C++11 there are some nice new convert functions from std::string to a number type.

where str is your number as std::string .

There are version for all flavours of numbers: long stol(string) , float stof(string) , double stod(string) . see http://en.cppreference.com/w/cpp/string/basic_string/stol

The possible options are described below:

1. sscanf()

This is an error (also shown by cppcheck) because "scanf without field width limits can crash with huge input data on some versions of libc" (see here, and here).

This solution is short and elegant, but it is available only on on C++11 compliant compilers.

3. sstreams

However, with this solution is hard to distinguish between bad input (see here).

4. Boost’s lexical_cast

However, this is just a wrapper of sstream , and the documentation suggests to use sstream for better error management (see here).

This solution is very long, due to error management, and it is described here. Since no function returns a plain int, a conversion is needed in case of integer (see here for how this conversion can be achieved).

6. Qt

Conclusions

Summing up, the best solution is C++11 std::stoi() or, as a second option, the use of Qt libraries. All other solutions are discouraged or buggy.

user avatar

To be fully correct you’ll want to check the error flags.

user avatar

use the atoi function to convert the string to an integer:

To be more exhaustive (and as it has been requested in comments), I add the solution given by C++17 using std::from_chars .

If you want to check whether the conversion was successful:

Moreover, to compare the performance of all these solutions, see the following quick-bench link: https://quick-bench.com/q/GBzK53Gc-YSWpEA9XskSZLU963Y

( std::from_chars is the fastest and std::istringstream is the slowest)

user avatar

1. std::stoi

2. string streams

3. boost::lexical_cast

4. std::atoi

5. sscanf()

Here is their example:

The following example treats command line arguments as a sequence of numeric data:

user avatar

Admittedly, my solution wouldn’t work for negative integers, but it will extract all positive integers from input text containing integers. It makes use of numeric_only locale:

The class numeric_only is defined as:

user avatar

It’s probably a bit of overkill, but boost::lexical_cast<int>( theString ) should to the job quite well.

user avatar

Well, lot of answers, lot of possibilities. What I am missing here is some universal method that converts a string to different C++ integral types (short, int, long, bool, . ). I came up with following solution:

Here are examples of usage:

Why not just use stringstream output operator to convert a string into an integral type? Here is the answer: Let’s say a string contains a value that exceeds the limit for intended integral type. For examle, on Wndows 64 max int is 2147483647. Let’s assign to a string a value max int + 1: string str = «2147483648». Now, when converting the string to an int:

x becomes 2147483647, what is definitely an error: string «2147483648» was not supposed to be converted to the int 2147483647. The provided function toIntegralType spots such errors and throws exception.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *