-2

I'm trying to convert a string into int32 in C++. In Python, I used to do:

import numpy as np
str = "HELLO"
np.array([str]).view(np.int32)

This results in:

array([72, 69, 76, 76, 79], dtype=int32)

i.e., the ord of each char.

How can I achieve the same in C++?

P. S. I'm not looking for Numpy-style way to accomplish this. But, looking for possible ways to obtain the same results.

7
  • To the downvoter, would you please post any comment regarding what is wrong with the question so that I can avoid in further questions. Commented Mar 31, 2019 at 20:50
  • Possible duplicate of NumPy style arrays for C++? Commented Mar 31, 2019 at 20:50
  • @zvone Nope, would you please read the new note I added? Commented Mar 31, 2019 at 20:52
  • So, you just want to convert string to int? Use atoi. BTW, also in Python I would not use numpy for that. I would just do int(s). Commented Mar 31, 2019 at 20:53
  • Man, have you really read the question. I'm aware of atoi, what it has to do with my question? Commented Mar 31, 2019 at 20:56

2 Answers 2

0

You could do something like:

auto arr = new int32_t[str.length()];

Then use std::transform as:

std::transform(str.begin(), str.end(), arr, [](char chr) -> int32_t { return int32_t(chr); });
Sign up to request clarification or add additional context in comments.

Comments

0

In Python, this is what it does:

>>> import numpy as np
>>> str = "HELLO"
>>> np.array([str]).view(np.int32)
array([72, 69, 76, 76, 79])

In C/C++, "HELLO" already is the same thing as [72, 69, 76, 76, 79]!

static const char *s = "HELLO";
printf("%d\n", s[0]);   // prints 72
printf("%d\n", s[1]);   // prints 69
int x = s[2];   // x is now 76
printf("%d\n", x);   // prints 76

2 Comments

The code you posted is erroneous. Also, this is the default int, I want int32_t.
@YassenHatem Eh, nit-picking does not really make a difference. Anyways, now the code is no longer erroneous. If you want int32_t instead of int just replace int with int32_t in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.