如何使用函数freopen_s [英] How to use function freopen_s
问题描述
为了从一个文本文件中读取输入,我写了下面code:
In order to read input from a text file, I wrote the following code:
int main(){
int x;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
scanf("%d", &x);
printf("%d\n", x);
system("pause");
return 0;
}
它的工作原理相当不错的。
It works quite good.
然而,在Visual Studio中,编译器给我的,因为freopen函数的错误,并建议我使用freopen_s来代替。我试着去了解函数如何freopen_s的作品,但我不能。我的code:
However, in visual studio, the compiler gives me an error because of freopen and suggests me to use freopen_s instead. I try to understand how function freopen_s works, but I can't. My code:
int main(){
int x;
#ifndef ONLINE_JUDGE
FILE *stream;
freopen_s(&stream, "input.txt", "r", stdin);
#endif
scanf("%d", &x);
printf("%d\n", x);
system("pause");
return 0;
}
这不输出任何东西,甚至是暂停不起作用。在CMD消失在程序完成没有任何印刷之后。我不知道为什么流,在freopen_s使用。谢谢你回答我的问题。
It does not output anything, and even the "pause" does not work. The cmd disappears right after the program finishes without anything printed. I don't know why the "stream" is used in freopen_s. Thank you for answering my question.
推荐答案
我建议您避免使用C风格的I / O库,并使用iostream库。它更安全,更清洁的解决方案。这里是打开一个文件并读取每行到控制台上的标准::字符串对象,并打印出样品code。
I would suggest you to avoid using the C style I/O library and use IOSTREAM Library. Its more safe and clean solution. Here is the sample code which opens a file and reads each line into the "std::string" object and prints on the console.
int main()
{
std::string file = "input.txt";
std::string line;
std::ifstream text_filestream(file.c_str());
while(std::getline(text_filestream, line)) {
std::cout<<line<<std::endl;
}
}
这篇关于如何使用函数freopen_s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!