0

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

4
Contributors
5
Replies
6
Views
9 Years
Discussion Span
Last Post by FumarMata
0

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

0

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;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.