Convert int to char then push back to vector - c++

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

Related

Difference between passing string S and string S[ ] in C++

void str(string S[])
{
S=S+"jg";
cout<<S;
}
In the above code, it throws me an error. I understand because I am passing the pointer S. But, when I remove the square brackets off, it doesn't throw me an error. What is the reason?
If string is really std::string then it have an overloaded operator for + that appends a std::string to another std::string.
And character literals can decay to a const char * which is implicitly convertible to std::string.
So without the square brackets you append two strings, and
S = S + "jg";
is really equivalent to
S = operator+(S, std::string("jg")); // Add S and "jg", assign result back to S
Which is equivalent to
S += "jg";
As for the reason it doesn't work with the square brackets, it's because then S is indeed a pointer, it's a pointer to string (i.e. string*).
Character literals are really arrays of constant characters, and as any array they decay to pointers to their first element.
That means the expression S + "jg" is trying to add values of the types string* and char const*, which is not possible and you get an error because of that.
if I understand you correctly
/*
accepts array of strings, but you must specify the size also
other wise function won't know the size of array;
example:
std::string[] arrOfStrings = {"venkat", "chary", "padala"};
str( arrOfStrings );
with size parameter;
str( arrOfStrings, 3 );
*/
void str( std::string s[] )
{
}
/*
accepts std::string
example: str( "abcdefg" );
*/
void str( std::string s )
{
}

C++ Constructor from char* to int[]/int*

I have a constructor with parameter char* (only numbers) and I would like make a simple mathematical operations. I thought to add new parameter to constructor int[]/int* to make it easier.
header:
class BigNum {
char *value;
int* arr;
public:
BigNum(char*, int * = 0) {};
BigNum();
};
cpp:
BigNum::BigNum(char* value, int *tab){
int length = sizeof(value) / sizeof(char*);
for (int i = 0; i < length; i++) {
arr[i] = value[i];
}
}
Can I do something like this? It does not even compile.
What I could to do to on this sample change char* to int.
its not even compile
It doesn't compile because you have defined BigNum(char*, int *) twice. Once in the header, and then in the source file.
Solution: Only define the constructor once. Extra hint: When a program doesn't compile, the compiler will tell you why in the diagnostic message.
This doesn't do what you think it does:
int length = sizeof(value) / sizeof(char*);
length will always be 1, because the type of value is char*. I suspect that your intention is that value points to an array and you want to calculate the length of that array. Well, calculating the length of an array from a pointer to an element of that array is not possible.
Solution: You have to a) pass the length of the array as an argument or b) specify that the array must be a terminated string, in which case you can calculate the length by iterating the string until the termination character is found.
You access arr[i] without initializing arr:
arr[i] = value[i];
The behaviour is undefined.
Solution: You have to allocate an array.
what i could to do to on this sample change char* to int.
It depends on how you want to change it. If you want to convert a pointed character digit to int, you can use the fact that digits are required to be sequential in all native character encodings (that are supported by C++). From that fact, we know that subtracting the value of digit character from the value of 0 character, we get the numeric value that the digit character represents:
char* c = address_of_some_digit;
int value_of_digit = '0' - *c;

how to get an integer from a char array

I have a char array that has '4''5'. But I want to convert those characters into actual integers so I subtract '0' from each index of the char array and store it into the same array. If I want to set an int called value to the 45 (the stuff inside the char array) How would I do it?
atoi() converts string to integer. For example if you already have the char array and integer variable declared you can do:
val = atoi(theCharArray);
Duplicate question
int int_value;
int_value = atoi(your_char_array);
the atoi() Function is used to convert string to int.
more information about atoi() Here.

Assign Static unsigned char* to std::vector<unsigned char>

I have following in my code:
static unsigned char* table;
...
table = something here;
Now I have to assign this table to variable of type std::vector<unsigned char> and I am unable to do so. I am doing:
unsigned char* buffer = (unsigned char*) table;
std::vector<unsigned char>::size_type size = strlen((const char*)buffer);
std::vector<unsigned char>static rawTable(buffer, buffer + size);
for(ByteBuffer::iterator it=rawTable.begin();it!=rawTable.end();++it)
std::cout << "Raw Table: "<<*it<< std::endl;
I am able to compile the code, but no value is there inside rawTable. Please help!
I have verified that variable table has value. I appreciate any help on this. Thanks.
strlen gives you the length of a string, not the size of an arbitrary memory region. If your table has a '\0' anywhere inside, strlen will find it and stop counting.
Also, by making rawTable a static variable, it will not update its value if buffer or size ever change. static variables are constructed only once.
Also, if this is supposed to be a table of numeric data, you should cast to a numeric non-character type. Otherwise cout may interpret it as ASCII codes.
You have a pointer of type unsigned char* pointing to an array.
Then you want to push every element of the array into a std::vector<unsigned char>, right?
If so, the key is to know the size of the array. You need to know the size beforehand. There's no way to determine the size of the array in the general case with some keyword or function if all that is visible to you is a pointer of type unsigned char*. You need to pass that information along with the pointer somehow.
In the case when the pointer of type unsigned char* points to an array of characters which is null-terminated (e.g. {'f', 'o', 'o', '\0'}), then you can use the C-string function strlen to count the number of characters in the array using only the pointer. However if the array is not null-terminated this will result in undefined behaviour.
When you have the size it's a simple matter to populate the std::vector with the arrays elements:
std::vector<unsigned char> v(arr, arr + size); // arr = pointer to array.
This is why you should use the containers in the standard library instead of raw arrays, as these containers internally keep track of the size and you can always access it with the size() function.
For constant size arrays use std::array. Example:
std::array<unsigned char, 3> arr{'f', 'o', 'o'}; // arr.size() == 3
// Print its contents.
for (auto c : arr) {
std::cout << c << std::endl;
}

string and char elements

I have an unsigned char* c that contains the element 0x1c. How can I add it into an std::vector<unsigned char>vect? I am working in c++.
std::vector<unsigned char>vect; //the vect dimention is dynamic
std::string at="0x1c";
c=(unsigned char*)(at.c_str());
vect[1]=c //error? why?
//The vect dimension is dynamic ONLY if you call push_back
std::vector <std::string> vect;
std::string at="0x1c";
vect.push_back(at);
If you are using C++, use std::string. The above code will copy your "0x1c" string into the vector.
If you try to do
vect[0] = c;
Without first expanding the vector with
vect.resize(1);
You will get segmentation fault because operator[] doesn't expand the the vector dynamically. The initial size of a vector is 0 btw.
UPDATE: According to the OP's comment, here is what he would want: copying a unsigned char * to a std::vector (i.e.copying a C array to a C++ vector)
std::string at = "0x1c";
unsigned char * c = (unsigned char*)(at.c_str());
int string_size = at.size();
std::vector <unsigned char> vect;
// Option 1: Resize the vector before hand and then copy
vect.resize(string_size);
std::copy(c, c+string_size, vect.begin());
// Option 2: You can also do assign
vect.assign(c, c+string_size);
c is an unsigned char*. vect is a std::vector<unsigned char>, so it contains unsigned char values. The assignment will fail, as operator [] on std::vector<unsigned char> expects an unsigned char, not a unsigned char *.
You have a hex representation of a character in a string, and you want the character?
easiest:
unsigned char c;
istringstream str(at);
str >> hex >> c; // force the stream to read in as hex
vect.push_back(c);
(I think that should work, have not tested it)
I just reread your question again, this line:
I have an unsigned char* c that
contains the element 0x1c
Does this mean that actually your unsigned char* looks like this:
unsigned char c[] = {0x1c}; // i.e. contains 1 byte at position 0 with the value 0x1c?
or my assumption above...
to print the vector out to cout, use a simple for loop, or if you are feeling brave
std::cout << std::ios_base::hex;
std::copy(vect.begin(), vect.end(), std::ostream_iterator<unsigned char>(std::cout, " "));
std::cout << std::endl;
this will print the hex representations of each of the unsigned char values in the vector separated by a space.