BrunoLM
BrunoLM

Reputation: 100341

How to read only the last 3 digits?

I want to get only the last 3 things from stdin.

Using

scanf("%3d")

I can get the first 3, but I want the last 3, and ignore everything before it.

Sample input

bkjashfsjak32326321536999999999999999999999999999999999999999999

How can I do that?

If possible I would like to ignore the contents on stdin and get only 3 chars on the buffer.

Upvotes: 1

Views: 1559

Answers (2)

jman
jman

Reputation: 11616

It looks like you're reading an integer. If so (since you're ignoring everything else), you can read the entire thing and take the remainder when divided by 1000.

    scanf ("%d", &read_int);
    last_3 = read_int % 1000;

Update: Since its not an integer (assuming some_large_buf can take your largest string):

    scanf ("%s", some_large_buf);
    last_3 = atoi (some_large_buf + strlen(some_large_buf) - 3);

Update 2: This version doesn't use a buffer, it maintains a rolling value of the least significant 3 digits.

    unsigned int sum = 0;
    char c;
    while (1) {
        scanf ("%c", &c);

        if (c == 0 || c == '\n') break;

        if (c >= '0' && c <= '9') {
            sum *= 10; 
            sum += c - '0';
            sum %= 1000;
        }   
        else {
            sum = 0;
        }   
    }   
    printf ("%d", sum);

Upvotes: 4

Mark Wilkins
Mark Wilkins

Reputation: 41222

One possibility would be to use fgets( ... stdin) to read it into a buffer. Then you could extract the desired information from the end of the buffer (e.g., use sscanf and pass the pointer to the desired start location). The general idea would be the following. Note that fgets can return a newline character in the returned buffer, so if it is known it will be there it would need to be accounted for.

char buf[1024];
char *pos;
size_t len;
int val = 0;

fgets( buf, sizeof( buf ), stdin );
len = strlen( buf );

if ( len < 3 )
  printf( "Not long enough\n" );
else
  sscanf( buf + len - 3, "%d", &val );

Upvotes: 2

Related Questions