Как в c преобразовать string в int
Перейти к содержимому

Как в c преобразовать string в int

  • автор:

C# how to convert a string to int

Time for a new post in my how-to series. In this series, I try to provide updated answers for common .NET/C# questions. I found that when googling common terms like "convert string to int", "write to a file", and similar, I would often get outdated StackOverflow answers, showing how to solve each problem with .NET 2 or even older. Even worse, most examples lack key aspects like exception handling and bad practices. For today's post, I will show you the best ways of converting strings to integers in C#.

C# how to convert a string to int

You have already tried converting a string to an int. Like parsing input from a text box in a system that didn't have modern model binding as we are used to today or when converting the output from a third-party API. While working for multiple companies both as a permanent and as a freelancer, I've seen a thousand lines of code, converting between data types. The most common pattern I've seen in C# is using the Parse -method:

While Parse provides a nice and simple interface for converting strings to int, it's rarely the right method to use. What happens if you provide something else than a number to the Parse -method:

As expected, the Parse -method throws a FormatException. I cannot count the times I've seen this construct:

Even documentation shows this approach as a valid way to parse ints. So, why is this a poor solution? Using exceptions as a control flow reduces the performance and makes your code harder to read. Luckily, .NET provides a much better way to parse ints without the need to catch exceptions: the TryParse -method:

TryParse returns a boolean indicating if the parameter ( s ) was successfully parsed or not. If parsed, the value will go into the out parameter ( i ). Parsing with a default value on an invalid string is still dead simple:

Convert.ToInt32

There's a Convert class in the System namespace that you may be aquainted with. Convert offers a range of methods for converting one data type to another. For converting strings to ints, it's an abstraction on top of the Parse method from the previous section. This means that you will need to catch the FormatException to use the ToInt32 -method:

While it might be nice with a common abstraction for converting data types, I tend not to use the Convert class. Being forced to control flow using exceptions is something I always try to avoid, which (to my knowledge) isn't possible with the Convert class. Besides this, there are some additional things that you will need to be aware of when using the ToInt32 -method. Take a look at the following code:

In the code, I'm converting the char 1 to an integer and writing it to the console. What do you expect the program to produce? The number 1 , right? That's not the case, though. The overload of the ToInt32 -method accepting a char as a parameter, converts the char to its UTF code, in this case 49 . I've seen this go down a couple of times.

To summarize my opinion about the Convert -class in terms of converting strings to integers, stick to the TryParse -method instead.

Exception handling

As long as you use the TryParse -method, there's no need to catch any exceptions. Both the Parse and the ToInt32 -method requires you to deal with exceptions:

Parsing complex strings

From my time working with financial systems, I was made aware of an overload of the TryParse -method that I don't see a lot of people using. The overload looks like this:

The parameter that I want to introduce you to is NumberStyles enum. The parameter accepts a bitwise combination of flags, allowing for more complex strings to be successfully parsed as integers. It's often much more readable to use this TryParse -overload, rather than doing a range of manipulations on the input string before parsing (like removing thousand separators, whitespaces, currency signs, etc.). Let's look at a couple of examples:

AllowParantheses will accept parantheses in the input string. But be aware that a parenthesized string is converted to a negative value. This format is often used in accounting and financial systems.

AllowCurrencySymbol will accept currency symbols inside the input string.

AllowThousands will accept a thousand separator in the input string.

Like any bitwise flag, multiple NumberStyles can be combined:

Parsing anti-patterns

When looking at code, I often see different anti-patterns implemented around int parsing. Maybe someone copies code snippets from StackOverflow or blog posts with unnecessary code, who knows. This section is my attempt to debunk common myths.

Trimming for whitespace

This is probably the most common code example I've seen:

By calling Trim the developer makes sure not to parse a string with whitespaces in the start and/or end. Trimming strings isn't nessecary, though. The TryParse -method automatically trims the input string.

Not using the TryParse overload

Another common anti-pattern is to do manual string manipulation to a string before sending it to the TryParse -method. Examples I've seen is to remove thousand separators, currency symbols, etc.:

Like we've already seen, calling the TryParse -overload with the AllowThousands flag (or one of the others depending in the input string) is a better and more readable solution.

Control flow with exceptions

We already discussed this. But since this is a section of anti-patterns I want to repeat it. Control flow with exceptions slow down your code and make it less readable:

As I already mentioned, using the TryParse -method is a better solution here.

Avoid out parameters

There's a bit of a predicament when using the TryParse -method. Static code analysis tools often advise against using out parameters. I don't disagree there. out parameters allows for returning multiple values from a method which can violate the single responsibility principle. Whether you want to use the TryParse -method probably depends on how strict you want to be concerning the single responsibility principle.

If you want to, you can avoid the out parameter (or at least only use it once) by creating a small extension method:

The method uses the built-in tuple support available in C# 7.

Convert to an array

A question that I often see is the option of parsing a list of integers in a string and converting it to an array or list of integers. With the knowledge already gained from this post, converting a string to an int array can be done easily with a bit of LINQ:

By splitting without parameters we get an enumerable of individual characters that can be converted to integers.

In most cases you would get a comma-separated list or similar. Parsing and converting that will require some arguments for the Split method:

By splitting the string on comma ( , ) we get the individual characters in between.

When working with external APIs, developers come up with all sorts of weird constructs for representing null or other non-integer values. To make sure that you only parse integers, use the Char.IsNumber helper:

By only including characters which are numbers, we filter values like null from the input string.

Преобразование строки в целое число в C#

В этом посте мы обсудим, как преобразовать строку в эквивалентное целочисленное представление в C#.

1. Использование Int32.Parse() метод

Чтобы преобразовать строковое представление числа в эквивалентное ему 32-разрядное целое число со знаком, используйте метод Int32.Parse() метод.

The Int32.Parse() метод выдает FormatException если строка не числовая. Мы можем справиться с этим с помощью блока try-catch.

2. Использование Int32.TryParse() метод

Лучшей альтернативой является вызов Int32.TryParse() метод. Он не генерирует исключение, если преобразование завершается неудачно. Если преобразование не удалось, этот метод просто возвращает false.

3. Использование Convert.ToInt32() метод

The Convert.ToInt32 можно использовать для преобразования указанного значения в 32-разрядное целое число со знаком.

Этот метод выдает FormatException если строка не числовая. Это можно решить с помощью блока try-catch.

Это все о преобразовании строки в целое число в C#.

Оценить этот пост

Средний рейтинг 5 /5. Подсчет голосов: 27

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования ��

Как в c преобразовать string в int

Converting string to int is a reoccurring task in the programming world. Despite being a simple task, many coders either fail or get confused while doing this. Conversion is mostly done so that we can perform operations over numbers that are stored as strings.

Example:

C is a strongly typed language. We’ll get an error if we try to input a value that isn’t acceptable with the data type. Not just in inputs but we will get an error while performing operations.

There are 3 methods to convert a string to int which are as follows:

  1. Using atoi( )
  2. Using Loops
  3. Using sscanf()

1. String Conversion using atoi( )

The atoi() function in C takes a character array or string literal as an argument and returns its value in an integer. It is defined in the <stdlib.h> header file.

If you observe atoi() a little closer you will find out that it stands for:

Breakdown of atoi() in simple terms

Breakdown of atoi() in simple terms

Example:

Atoi behaves a bit differently for string. Let’s check how:

Example:

Explanation:

  • “Geek 12345” here ‘Geek’ is the first word so the answer will be : 0 (No number)
  • “12345 Geek” here ‘12345’ is the first word so the answer will be: 12345

2. Using Loops

We can use loops to convert a string to an integer by traversing each element of the string one by one and comparing the number characters to their ASCII values to get their numeric values and using some mathematics for generating the integer. The below example demonstrates how to do it.

Example:

Note: We have used str[i] – 48 to convert the number character to their numeric values. For e.g. ASCII value of character ‘5’ is 53, so 53 – 48 = 5 which is its numeric value.

3. Using sscanf()

We can use sscanf() to easily convert a string to an integer. This function reads the formatted input from the string.

Syntax of sscanf:

Parameters:

  • source – source string.
  • formatted_string – a string that contains the format specifiers.
  • … : – variable arguments list that contains the address of the variables in which we want to store input data.

There should be at least as many of these arguments as the number of values stored by the format specifiers. On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.

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?

25 Answers 25

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.

Claudio's user avatar

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

Winston Ewert's 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)

Nikolas Hamilton's 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:

Claudio's 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:

Nawaz's user avatar

In C++11 we can use "stoi" function to convert string into a int

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

Thomas Weller's 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 не будет опубликован. Обязательные поля помечены *