[英]Issues with atoi() when converting numbers in a string to an integer
I have been running into this funny issue with using atoi() in C for an assignment.我在 C 中使用 atoi() 进行分配时遇到了这个有趣的问题。 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.我正在使用 strncpy() 来帮助获取字符串中我需要的数字并将它们复制到 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.我应该将 '15' 存储在 RimDiameter 中,但是一旦我使用 atoi(RimDiameter) 我会在 x 中存储 0 而不是 '15' ,这是我的 if/else 语句正常工作所必需的。
Anyone have any idea why I would be getting this issue?任何人都知道为什么我会遇到这个问题?
This is a place where sscanf is really useful:这是 sscanf 真正有用的地方:
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您可以尝试多种不同的字母/数字模式,以查看哪一个与 if...else if...else if... 链匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.