'use freopen() and scanf() to read an int from file
I try to read an int from a file using freopen(). File in.txt simply have a number:1, but what I get in output is -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?
Solution 1:[1]
rule #1, if you have file io then check the return values
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
int count = scanf("%d", &t);
if(count != 1){
printf("bad number");
return -1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
