简体   繁体   中英

Convert int to char then push back to vector

i'm having an issue converting an int into a char. Code looks like:

 int main {
  int i = 10;
  char c[80];
  std::vector<char> data; 

  sprintf(i,"%d",c);
  data.push_back(c)
}

But I keep getting a invalid conversion from char* to std::vector... error. Is there an easier way to convert an integer into a character and then store it inside a vector that holds chars? Because of an earlier task I need to first bring in the value as an int and I need to bring that integer 10 into the vector as '10'.

For starters it seems there is a typo

sprintf(text,"%d",f);

You nean

sprintf( c ,"%d", i );

The value type of this vector

std::vector<char> data;

is char . So in the member function push you have to supply an expression that has the type char . However in this call

data.push_back(c);

you supplied an object of an array type

char c[80];

If you want to store in the vector a character representation of a number as separate characters then you can write for example

size_t n = strlen( c );
data.reserve( n );
data.assign( c, c + n );

Or you could declare the vector initializing it by the representation of the number like

std::vector<char> data( c, c + n );

If you want to store the whole number as one element of the vector then you should declare the vector like

std::vector<std::string> data( 1, std::to_string( i ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM