-1

I'm unable to convert a char to an int and I have no idea why.

I simply want to convert some data that I parse from a CSV from string to int and the compiler won't let me.

I get this error:

invalid cast from type '__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> > >::value_type {aka std::__cxx11::basic_string<char>}' to type 'int'

Note I have also tried:

static_cast<int>(data[2]);

and even

'a' - data[2];

Am I missing something? I feel like I've done this a million times.

time_t startDate;
string ID;
int beds;
int numDays;
string token;
vector<string> data;

for(int i = 0; i < 2; i++){ // run through the rest of the file
    getline(customers, line);
    stringstream s(line); // to parse the csv

    while(getline(s,token, ',')){
        data.push_back(token);
    }

    startDate = changeToInt(data[0]);
    ID = data[1];
    ---> beds = (int)data[2];
    ---> numDays = (int)data[3];
NAND
  • 663
  • 8
  • 22
Trisitian
  • 71
  • 1
  • 1
  • 6

3 Answers3

5

data is a vector of strings.

Therefore data[0] is a single string.

There is no clear conversion from "Hello World" (a string) to an int.

The error message is correct.

If you're confident the string is int-like (such as "1234"), then I recommend std::stoi().

abelenky
  • 63,815
  • 23
  • 109
  • 159
1

You want to parse the string and convert it to an int using a function like std::stoi(). You cannot use a cast to do it.

NAND
  • 663
  • 8
  • 22
user2199860
  • 788
  • 4
  • 14
1

You are trying to convert string to int, not char to int, to convert string to int, you can use std::stringstream;

If value converted is out of range for int data type, stringstream returns INT_MIN or INT_MAX.

std::stringstream ss("");

ss << data[1];

ss >> ID;
NAND
  • 663
  • 8
  • 22
pvc
  • 1,070
  • 1
  • 9
  • 14