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?
gets!strncpy; its behavior is not what most people expect. See for instance stackoverflow.com/questions/1453876/…%cis the wrong format specifier to print a decimal integer; you probably want%d.strncpy()does not automatically terminate the string: do it yourself...strncpy(RimDiameter, TireCode+8, 2); RimDiameter[2] = 0;