bahadirtr
bahadirtr

Reputation: 53

atoi and string array

I have a string array and an integer array. I want to convert the elements of string array to integer and then store them in the integer array. I wrote this code :

string yuzy[360];
int yuza[360];

for(int x = 0;x<360;x++)
{
    if(yuzy[x].empty() == false)
    {

         yuza[x]=atoi(yuzy[x]);
         cout<<yuza[x]<<endl;
    }
    else
        continue;
}

this piece of code gives this error: error: cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'int atoi(const char*)'

When I write the content of the string (-75dbm) in atoi function it works fine. But when I write (yuzy[x]), I get the error. How can I make atoi works well with string array? Thanks.

Upvotes: 0

Views: 9004

Answers (3)

juanchopanza
juanchopanza

Reputation: 227468

As an alternative to atoi, you could use std::stoi and related functions, if you have C++11 support.

yuza[x] = std::stoi(yuzy[x]);

Upvotes: 3

B&#236;nh Nguy&#234;n
B&#236;nh Nguy&#234;n

Reputation: 2352

atoi accept a c-style string as parametter, so, you could use atoi(yuzy[x].c_str());

Upvotes: 1

user529758
user529758

Reputation:

atoi() takes C strings (char pointers) and not C++ string objects. Use

atoi(yuzy[x].c_str());

instead.

Upvotes: 8

Related Questions