C - fscanf无法从文本文件中正确读取数字

时间:2016-02-19 20:07:55

标签: c pointers reference scanf

我是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);
}

1 个答案:

答案 0 :(得分:0)

您的代码看起来是正确的,但您应该在fopen之前测试fscanf是否有效。顺便说一下,你获得的数字是int的最大值 您的文件可能存在问题:

  • 没有读取权限
  • 文件不存在
  • 不包含正确的值

另外,如果只使用C函数,为什么要使用C ++?

相关问题