4

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?

4

5 回答 5

12

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.

于 2008-10-11T05:52:55.230 回答
4

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).

于 2008-10-11T05:50:13.330 回答
2

您的示例不完整,因为您没有说出向量的确切类型。我假设它是 std::vector<char> (也许,你用 C 字符串中的每个字符填充)。

我的解决方案是在 char * 上再次转换它,这将提供以下代码:

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

请注意,这是一个类似 C 的解决方案(即,在 C++ 代码中非常难看),但它仍然有效。

于 2008-10-11T15:43:16.830 回答
2
const char tempChar = token.at(0);
int tempVal = atoi(&tempChar);
于 2012-02-20T14:41:46.613 回答
1
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;
}
于 2008-10-11T06:21:59.740 回答