简体   繁体   中英

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.

#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 . By the way, the number you get is the maximum value for an int There is probably a problem with your file:

  • No read permission
  • file does not exist
  • does not contain the right value

Also, why do you use C++ if you only use C functions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM