Concat'ing intergers to make a string
This is what I am trying to do:开发者_开发知识库
int x = 0;
char toBuffer;
while (twenty_byte_buffer[x] != '\0') // While the string isn't at the end...
{
cout << int(twenty_byte_buffer[x]); // show me, works fine
//need to concat the int values from above into toBuffer as a string
//eg. "-62-8711097109" would have derived from this "©nam"
//this doesn't work:
//strcat ( toBuffer, reinterpret_cast<*????*>(twenty_byte_buffer[x]) );
x++;
}
Any help will be greatly appreciated!
Use a stringstream
. It works just like cout
:
stringstream sstr;
while (twenty_byte_buffer[x] != '\0')
{
sstr << int(twenty_byte_buffer[x]);
x++;
}
string result = sstr.str();
The easiest option would be a std::stringstream
:
#include <sstream>
#include <iostream>
using namespace std;
int main(){
stringstream numbers;
for(int i=0; i < 10; ++i){
numbers << i;
}
cout << numbers.str() << endl; // prints "0123456789"
}
#include<sstream>
std::stringstream sout;
while (twenty_byte_buffer[x] != '\0') // While the string isn't at the end...
{
cout << int(twenty_byte_buffer[x]); // show me, works fine
sout << int(twenty_byte_buffer[x]); //concatenating into stringstream!
x++;
}
std::string str = sout.str(); //get the string value!
cour << str ;
The right answer depends on what's really inside your twenty_byte_buffer
.
If the values in twenty_byte_buffer
are ASCII characters that represent integers (having the values '0' through '9', inclusive), then the stringstream solution that Daniel Gallagher posted would need to be revised slightly, removing the (int)
cast:
stringstream sstr;
int x = 0;
while (twenty_byte_buffer[x] != '\0')
{
// Note no cast to int here...
sstr << twenty_byte_buffer[x];
x++;
}
string result = sstr.str();
But if the bytes in the buffer represent binary integers (having the values [-128 - 127], inclusive), then the while
condition appears to be wrong: The loop will exit on the first 0 value that it encounters! (To use unsigned integers, in the range [0 - 255], change the cast to (unsigned int)
.)
By the way, the reason why your char toBuffer
solution didn't work is twofold:
1) You need to use an array of chars, not a single char. You could declare toBuffer as char toBuffer[100]
, for example (and then be sure to initialize at least the first char to '\0'
.)
2) The strcat
would still fail if the bytes represent binary values (unsigned ints in the range [0..255], or ints in the range [-128..127]). You need a call that converts those values to their binary representation. One way of doing this uses the non-standard but commonly-supported itoa
call:
char toBuffer[100];
int x = 0;
int y = 0;
// I think we still need a different terminating condition...
while (twenty_byte_buffer[x] != '\0') {
itoa(bytes[x], &toBuffer[y], 10));
y += strlen(&toBuffer[y]);
}
精彩评论