Atoi () conversion error

atoi () gives 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 the token is a vector

how can i get around this?

+3
source share
5 answers

token.at (0) returns a single char, but atoi () expects a string (a pointer to char.) Either converts a single character to a string, or converts a single char to the number that it represents, you can usually * just do this:

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

* The exception is that the encoding does not encode the numbers 0-9, which is extremely rare.

+10
source

You will need to create a line:

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

... , std::vector char std::string, ( , , ).

+3

Your example is incomplete since you are not saying the exact type of vector. I assume this is std :: vector <char> (which perhaps you filled each char from line C).

My solution would be to convert it again to 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) ;
}

Please note that this is a C-shaped solution (i.e. rather ugly in C ++ code), but it remains effective.

+1
source
const char tempChar = token.at(0);
int tempVal = atoi(&tempChar);
+1
source
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;
}
0
source

Source: https://habr.com/ru/post/1698166/


All Articles