Вопрос

For instance, Let's say I have the following:

char str[] = "33MayPen5";
int length = strlen(str);
char buffer[length];
int j = 0;

for(int i = 0; i < length; i++) {

    buffer[j] = // I would like to read the number 33 from str and store it in buffer[0]
    j++;
}

Basically, I would like to store str[0] AND str[1] which is 33, into buffer[0]. How would I accomplish such a task? Thanks In Advance!

Это было полезно?

Решение

Please provide code which is correctly formed, you have an error on this line:

char buffer[length];

You lenght must be const. You can solve this by reading each nomber and convert it to int. But no way to store 33 at once.

Другие советы

If I have understood correctly you need something as

char str[] = "33MayPen5";
int length = strlen(str);
char *buffer = new char[length];
int j = 0;

for ( int i = 0; i < length && std::isdigit( str[i] ); i++ ) 
{

    buffer[j++] = str[i];
}

Or if you need to store all digits from str in buffer then the loop can look as

for ( int i = 0; i < length; i++ ) 
{

    if ( std::isdigit( str[i] ) ) buffer[j++] = str[i];
}

Of course it would be better if you would use std::string instead of the dynamically allocated array.

In this case the both examples would look as

std::string buffer;
buffer.reserve( length );

for ( int i = 0; i < length && std::isdigit( str[i] ); i++ ) 
{
    buffer.push_back( str[i] );
}

and

std::string buffer;
buffer.reserve( length );

for ( int i = 0; i < length; i++ ) 
{

    if ( std::isdigit( str[i] ) ) buffer.push_back( str[i] );
}

EDIT: I see you changed your post.

When the code could look as

char str[] = "33MayPen5";
int length = strlen(str);
unsigned char *buffer = new unsigned char[length];

unsigned char c = 0;

for ( int i = 0; i < length && std::isdigit( str[i] ); i++ ) 
{

    c = c * 10 + str[i];
}
buffer[0] = c;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top