1

I have an std::array<unsigned, 3> defined inside a class. I want to initalise it inside the constructor, like this:

MyClass::MyClass(std::map<std::string, std::string> const&data)
{
MyArr[0] = (unsigned)(std::atoi(data["one"].c_str()));
MyArr[1] = (unsigned)(std::atoi(data["two"].c_str()));
MyArr[2] = (unsigned)(std::atoi(data["three"].c_str()));
}

By compiling this code in the latest MSVC release with

cl /EHsc /O2 /std:c++17 main.cpp

I get

error C2397: conversion from 'int' to 'unsigned int' requires a narrowing conversion

it points to the line 2 if the snippet.

Terens Tare
  • 129
  • 1
  • 14
  • 1
    Fyi, line 2 of the snippet is an open brace. You mean the assignment to `MyArr[0]`, yes (no) ? – WhozCraig Apr 13 '20 at 11:30
  • 2
    It is not possible to call `operator[]` on const object, your map is marked as const. Also use `std::stoul` instead of atoi. – rafix07 Apr 13 '20 at 11:33
  • see [Why shouldn't I use atoi()?](https://stackoverflow.com/q/17710018/995714). use `std::stoul` instead which receives a std::string directly and you won't need `.c_str(0)`. [How can I convert a std::string to int?](https://stackoverflow.com/a/7664227/995714) – phuclv Apr 13 '20 at 11:35
  • Thank you everyone. `std::stoul` did the trick for me. – Terens Tare Apr 13 '20 at 16:42

1 Answers1

0

Use the appropriate function to convert string to an unsigned integer:

char* end;
MyArr[0] = std::strtoul(data["one"].c_str(), &end, 10);

You might also need to define your array as std::array<unsigned long, 3>.

Igor R.
  • 14,716
  • 2
  • 49
  • 83
  • 1
    [`std::stoul`](https://en.cppreference.com/w/cpp/string/basic_string/stoul) is better because it accepts std::string – phuclv Apr 13 '20 at 11:36