gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:04:55 28 4
gpt4 key购买 nike

我是 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/

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