我是 C 新手,我试图让我的 int 等于 4。4 是从文本文件中读取的,但是当我打印出来时,它打印出 32767。
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include "Component.h"
using namespace std;
int main(int argc, char** argv) {
FILE *fp;
fp=fopen("text.txt","r");
int a;
fscanf(fp,"%d",&a);
if(fp == NULL) {
printf("cannot open");
}
printf("%d",a);
}
最佳答案
您的代码看起来是正确的,只是您应该在 fscanf
之前测试 fopen
是否工作。顺便说一句,您得到的数字是 int
的最大值
您的文件可能有问题:
- 没有读取权限
- 文件不存在
- 不包含正确的值
另外,如果你只使用 C 函数,为什么还要使用 C++?
关于C - fscanf 未从文本文件中正确读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35514044/