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?

7
  • 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. Commented May 1, 2021 at 17:39
  • 1
    Never ever ever use gets! Commented May 1, 2021 at 17:41
  • 2
    Also, you should carefully read the documentation of strncpy; its behavior is not what most people expect. See for instance stackoverflow.com/questions/1453876/… Commented May 1, 2021 at 17:43
  • 2
    And %c is the wrong format specifier to print a decimal integer; you probably want %d. Commented May 1, 2021 at 17:44
  • strncpy() does not automatically terminate the string: do it yourself...strncpy(RimDiameter, TireCode+8, 2); RimDiameter[2] = 0; Commented May 1, 2021 at 17:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.