[英]C - fscanf not reading number correctly from text file
I am new to C and I am trying to make my int a equal to 4. The 4 is being read from a text file however when I print a out it prints out 32767. 我是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);
}
Your Code looks right, except that you should test if fopen
worked before fscanf
. 您的代码看起来正确,除了您应该在fscanf
之前测试fopen
起作用。 By the way, the number you get is the maximum value for an int
There is probably a problem with your file: 顺便说一句,您获得的数字是一个int
的最大值。您的文件可能存在问题:
Also, why do you use C++ if you only use C functions? 另外,如果仅使用C函数,为什么还要使用C ++?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.