简体   繁体   English

使用 freopen() 和 scanf() 从文件中读取一个 int

[英]use freopen() and scanf() to read an int from file

I try to read an int from a file using freopen().我尝试使用 freopen() 从文件中读取一个 int。 File in.txt simply have a number:1, but what I get in output is -858993460.文件in.txt只有一个数字:1,但我在 output 中得到的是 -858993460。 My code is shown below:我的代码如下所示:

#include <cstdio>
#pragma warning(disable:4996)
using namespace std;

int main()
{
    freopen("in.txt", "r", stdin);
    int t;
    scanf("%d", &t);
    printf("%d\n", t);
    return 0;
}

Why does scanf() not read from in.txt correctly?为什么 scanf() 不能正确读取in.txt

rule #1, if you have file io then check the return values规则 #1,如果你有文件 io 然后检查返回值

int main()
{
    FILE * ret = freopen("in.txt", "r", stdin);
    if(ret == NULL){
       printf("failed to open file");
       return -1;
    }
    int t;
    scanf("%d", &t);
    printf("%d\n", t);
    return 0;
}

your code runs fine for me once I point it at a real file一旦我将它指向真实文件,你的代码对我来说运行良好

also check the return from scanf还要检查 scanf 的返回

 int count = scanf("%d", &t); 
 if(count != 1){
     printf("bad number");
     return -1;
 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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