Hello

I have written my program and right now I am stuck in something that I thought that was going to be easy.

I have the char buffer, which receives from the serial port some letters and 2 numbers at position 3, lenght 2. I want to extract those numbers and place them to an int to make numeric comparisons.

I am quite new at C, in other languages it would have been so easy, but I'm totally stuck in this...

Thanks!

marc

have a read about the atoi() function

Hello Freaky_Chris

Thanks for your answer, but atoi() doesn't work for me. I have chars like R1H81R1, and I need only the 81 in the middle, but not any other number in the char. As I understand, atoi would return me 1811 instead of the 81 that I need

Thank you

int x;
	sscanf(str,"%*c%*d%*c%d", &x);

well if you know the exact position of those chars you can easily extract them from the string you read them in... for example, the given the position and length of the integer, you could go with something like this:

#include <cstdio>

char str[ 256 ];
int pos, len, sol = 0;

int main( void )
{
    scanf( "%s", str );
    scanf( "%d%d", &pos, &len );
    
    for( int i = pos; i < pos + len; ++i ) {
         sol *= 10; sol += str[i] - '0';
    }
    
    printf( "%d\n", sol );
    
    scanf( "\n" );
    return 0;
}

thanks ivailosp and gregorynoob, that worked perfectly! :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.