gpt4 book ai didi

c - 如何检查变量是否为整数类型

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:08 25 4
gpt4 key购买 nike

我只是想检查变量中存在的值是否为整数。

My program below reads two values from "myfile.txt" and performs addition if and only if they are integers otherwise it returns "Invalid Output". I have successfully read values from "myfile.txt" but i have no way of checking whether the two values are integer or not.How to perform this test?

#include <stdio.h>
#include <conio.h>

int main()
{
FILE *fp;
int i, mkji, num, num1, num2;
int s = 0;
int a[2];
char term, term2;
clrscr();
fp = fopen("myfile.txt", "r+");
if (fp != 0)
{
for(i = 0; i < 2; i++)
{
fscanf(fp, "%d", &a[i]);
}
for(i = 0; i < 2; i++)
{
printf("%d\n", a[i]);
}
num = a[0];
num1 = a[1];
num2 = num + num1;
printf("%d", num2);
mkji = fclose(fp);
}
else
printf("FILE CANNOT BE OPEN");
getch();
return 0;
}

最佳答案

检查fscanf 的返回值。 fscanf 返回成功扫描的项目数,如果出现 IO 错误,则返回 -1。因此,如果数字格式不正确,fscanf("%d",&a[i]); 应该返回 0。

关于c - 如何检查变量是否为整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com