How to Convert a C++ String to an Int

How to convert a string to integer in C?

There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);

You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
/* Could not convert. */

Anyway, stay away from atoi:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be
represented, the behavior is undefined
.

Converting a C string to individual integers


char numbers[] = "a";

This creates an array of 2 char items. That's not sufficient for anything reasonable. Use a std::string instead.

cin >> numbers;

Better use std::getline from the <string> header.

sum += atoi(numbers[i]);

atoi takes a string as argument, not a single char. You want the sum of the digits, not the sum of the number values you get by applying atoi to all right substrings of the specification.

For a digit character ch, the corresponding digit value is ch - '0'.

How can I convert String to Int?

Try this:

int x = Int32.Parse(TextBoxD1.Text);

or better yet:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}

If you are curious, the difference between Parse and TryParse is best summed up like this:

The TryParse method is like the Parse
method, except the TryParse method
does not throw an exception if the
conversion fails. It eliminates the
need to use exception handling to test
for a FormatException in the event
that s is invalid and cannot be
successfully parsed. - MSDN

Convert string into number

Yes. You can use strtol function.

long int strtol(const char * restrict nptr, char ** restrict endptr, int base);  

The strtol convert the initial portion of the string pointed to by nptr to long int representation.

Better to not use atoi. It tells noting when unable to convert a string to integer unlike strtol which specify by using endptr that whether the conversion is successful or not. If no conversion could be performed, zero is returned.

Suggested reading: correct usage of strtol

Example:

char *end;
char *str = "test";
long int result = strtol(str, &end, 10);

if (end == str || *temp != '\0')
printf("Could not convert '%s' to long and leftover string is: '%s'\n", str, end);
else
printf("Converted string is: %ld\n", result);

C++ convert string to int

You can check the number of characters processed.

string str2 = "31337 test"; 
std::size_t num;

int myint2 = stoi(str2, &num); // 31337
// ^^^^

// num (the number of characters processed) would be 5
if (num != str2.length()) {
...
}

Convert string to int in C# (When String is 'E0305' To convert Int is not Work)

If you just want to skip invalid string value, it is better to use TryParse instead of returning 0 (which might be valid value). At your calling code it should look like this:

string val = "F0005";
if (int.TryParse(val, out int i) {
// parse success. you can use i here
}
else {
// parse failed.
}

If you really want it to be 0, this should work

string val = "F0005";
int i = int.TryParse(val, out int x) ? x : 0;


Related Topics



Leave a reply



Submit