C++ Parse Int from String

c++ parse int from string

  • In C++11, use std::stoi as:

     std::string s = "10";
    int i = std::stoi(s);

    Note that std::stoi will throw exception of type std::invalid_argument if the conversion cannot be performed, or std::out_of_range if the conversion results in overflow(i.e when the string value is too big for int type). You can use std::stol or std:stoll though in case int seems too small for the input string.

  • In C++03/98, any of the following can be used:

     std::string s = "10";
    int i;

    //approach one
    std::istringstream(s) >> i; //i is 10 after this

    //approach two
    sscanf(s.c_str(), "%d", &i); //i is 10 after this

Note that the above two approaches would fail for input s = "10jh". They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):

int to_int(char const *s)
{
if ( s == NULL || *s == '\0' )
throw std::invalid_argument("null or empty string argument");

bool negate = (s[0] == '-');
     if ( *s == '+' || *s == '-' ) 
        ++s;

if ( *s == '\0')
throw std::invalid_argument("sign character only.");

     int result = 0;
     while(*s)
     {
          if ( *s < '0' || *s > '9' )
throw std::invalid_argument("invalid input string");
          result = result * 10  - (*s - '0');  //assume negative number
          ++s;
     }
     return negate ? result : -result; //-result is positive!

This solution is slightly modified version of my another solution.

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
.

How to parse a string to an int in C++?

In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.

int myNr = std::stoi(myString);

It will throw an exception on conversion error.

Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11".

See more: http://en.cppreference.com/w/cpp/string/basic_string/stol

How to parse sequence of integers from string in C?

As I noted in comments, it is probably best to use strtol() (or one of the other members of the strtoX() family of functions) to convert the string to integers. Here is code that pays attention to the Correct usage of strtol().

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char *line = NULL;
size_t len = 0;

while (getline(&line, &len, stdin) != -1)
{
printf("Line input : [%s]\n", line);
int val = atoi(line);
printf("Parsed integer: %d\n", val);

char *start = line;
char *eon;
long value;
errno = 0;
while ((value = strtol(start, &eon, 0)),
eon != start &&
!((errno == EINVAL && value == 0) ||
(errno == ERANGE && (value == LONG_MIN || value == LONG_MAX))))
{
printf("%ld\n", value);
start = eon;
errno = 0;
}
putchar('\n');
}
free(line);
return 0;
}

The code in the question to read lines using POSIX getline() is almost correct; it is legitimate to pass a pointer to a null pointer to the function, and to pass a pointer to 0. However, technically, getline() returns -1 rather than EOF, though there are very few (if any) systems where there is a difference. Nevertheless, standard C allows EOF to be any negative value — it is not required to be -1.

For the extreme nitpickers, although the Linux and macOS man pages for strtol() state "returns 0 and sets errno to EINVAL" when it fails to convert the string, the C standard doesn't require errno is set for that. However, when the conversion fails, eon will be set to start — that is guaranteed by the standard. So, there is room to argue that the part of the test for EINVAL is superfluous.

The while loop uses a comma operator to call strtol() for its side-effects (assigning to value and eon), and ignores the result — and ignoring it is necessary because all possible return values are valid. The other three lines of the condition (the RHS of the comma operator) evaluate whether the conversion was successful. This avoids writing the call to strtol() twice. It's possibly an extreme case of DRY (don't repeat yourself) programming.

Small sample of running the code (program name rn89):

$ rn89
1 2 4 5 5 6
Line input : [ 1 2 4 5 5 6
]
Parsed integer: 1
1
2
4
5
5
6

232443 432435423 12312 1232413r2
Line input : [232443 432435423 12312 1232413r2
]
Parsed integer: 232443
232443
432435423
12312
1232413

324d
Line input : [324d
]
Parsed integer: 324
324

$

Convert part of a string to int in one command in C

can I do this in one line, instead of using a temp string?

Use sscanf() for a quick dirty no-temp.

int n;
// v--- scan width limit
// | v---------------v
if (sscanf(MY_STRING + INT_START, "%*d", INT_END-INT_START, &n) == 1) {
puts("Success");
}

Better code would consider trouble with overflow.


OP's code is no good as temp is not certain to point to a string. It may lack a null character.

strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
int n = atoi(temp); // bad

How to convert an int to string in C?

EDIT: As pointed out in the comment, itoa() is not a standard, so better use sprintf() approach suggested in the rivaling answer!


You can use itoa() function to convert your integer value to a string.

Here is an example:

int num = 321;
char snum[5];

// convert 123 to string [buf]
itoa(num, snum, 10);

// print our string
printf("%s\n", snum);

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

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



Related Topics



Leave a reply



Submit