views:

1566

answers:

5

atoi() is giving me this error:


error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
        Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast

from this line: int pid = atoi( token.at(0) ); where token is a vector

how can i go around this?

+3  A: 

You'll have to create a string:

int pid = atoi(std::string(1, token.at(0)).c_str());

... assuming that token is a std::vector of char, and using std::string's constructor that accepts a single character (and the number of that character that the string will contain, one in this case).

Jason Etheridge
from what I remember, it's std::string(token.at(0), 1)
Lev
Other way around: number of characters, and the character. But you're right otherwise, Lev.
Jason Etheridge
+9  A: 

token.at(0) is returning a single char, but atoi() is expecting a string (a pointer to a char.) Either convert the single character to a string, or to convert a single digit char into the number it represents you can usually* just do this:

int pid = token.at(0) - '0';

* The exception is when the charset doesn't encode digits 0-9 in order which is extremely rare.

yjerem
Any exception would also be non-compliant. The C++ standard [lex.charset] mandates that '0' - '9' have consecutive numerical values.
Charles Bailey
A: 

I am getting this error: error C2440: '' : cannot convert from 'char' to 'std::string' No constructor could take the source type, or constructor overload resolution was ambiguous

when I do it this way:

int pid = atoi(std::string(token.at(0)).c_str());

and a runtime error when I do it this way

int pid = token.at(0) - '0';
What exactly are you storing inside the vector?To fix the string converting problem, try this instead: std::string(1, token.at(0))
yjerem
A: 
stringstream ss;
ss << token.at(0);
int pid = -1;
ss >> pid;

Example:

#include <iostream>
#include <sstream>
#include <vector>

int main()
{
  using namespace std;

  vector<char> token(1, '8');

  stringstream ss;
  ss << token.at(0);
  int pid = -1;
  ss >> pid;
  if(!ss) {
    cerr << "error: can't convert to int '" << token.at(0) << "'" << endl; 
  }

  cout << pid << endl;
  return 0;
}
J.F. Sebastian
+1  A: 

Your example is incomplete, as you don't say the exact type of the vector. I assume it is std::vector<char> (that, perhaps, you filled with each char from a C string).

My solution would be to convert it again on char *, which would give the following code:

void doSomething(const std::vector & token)
{
    char c[2] = {token.at(0), 0} ;
    int pid   = std::atoi(c) ;
}

Note that this is a C-like solution (i.e., quite ugly in C++ code), but it remains efficient.

paercebal