0

I have been running into this funny issue with using atoi() in C for an assignment. Im gonna paste a bit of the code I have so far...

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define _CRT_SECURE_NO_WARNINGS
 char RimDiameter[15];
 char TireCode[15];
int x;
 puts("Enter the code on the Tire");  // P215/65R15 95H
gets(TireCode);
strncpy(RimDiameter, TireCode+8, 2); // TireCode = P215/65R15 95H, RimDiameter = 15
int x = atoi(RimDiameter);    // where I'm having issues
 if(x >=14 && x <=22)
{
 printf("%c is valid\n", x);
}
else
{
printf("%c is invalid\n", x);
}

I'm using strncpy() to help grab the numbers I need in the string and copy them to RimDiameter. I should have '15' stored in RimDiameter but once I use atoi(RimDiameter) I get 0 stored in x instead of '15' which is needed for my if/else statements to work properly.

Anyone have any idea why I would be getting this issue?

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • 1
    I've added code block formatting around your code; can you please do this yourself in the future? Then the double-spacing is not required. Also, proper indentation would help a lot. – Nate Eldredge May 01 '21 at 17:39
  • 1
    [**Never ever ever use `gets`!**](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Nate Eldredge May 01 '21 at 17:41
  • 2
    Also, you should carefully read the documentation of `strncpy`; its behavior is not what most people expect. See for instance https://stackoverflow.com/questions/1453876/why-does-strncpy-not-null-terminate – Nate Eldredge May 01 '21 at 17:43
  • 2
    And `%c` is the wrong format specifier to print a decimal integer; you probably want `%d`. – Nate Eldredge May 01 '21 at 17:44
  • `strncpy()` does not automatically terminate the string: do it yourself...`strncpy(RimDiameter, TireCode+8, 2); RimDiameter[2] = 0;` – pmg May 01 '21 at 17:44
  • `#define _CRT_SECURE_NO_WARNINGS` should go before your includes – Nasrat Takoor May 01 '21 at 17:44
  • What is the content of the array RimDiameter when you call atoi? I – JJF May 01 '21 at 18:25

1 Answers1

1

This is a place where sscanf is really useful:

int p, r, d, h;
char TireCode[256];

fputs("Enter the code on the tire: ", stdout);
if (!fgets(TireCode, sizeof(TireCode), stdin)) {
    fprintf(stderr, "Unexpected EOF");
} else if (sscanf(TireCode(" P%d /%dR%d%d", &p, &r, &d, &h) == 4) {
    if (d >= 14 && d <= 22) {
        printf("%d is valid\n");
    } else {
        printf("%d is invalid\n");
    }
} else {
    fprintf(stderr, "Input is not in the expected format");
}

You can try multiple different patterns of letters/numbers to see which one matches with an if...else if...else if... chain

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226