【发布时间】:2021-09-25 13:24:22
【问题描述】:
我是竞争性编程的新手,最近才开始接触它。我开始学习 C++ 以进行竞争性编程。从我阅读的所有资源中,我了解到我们需要准备一些后端功能,以便我们在比赛中快速。所以,我已经准备好了所有这些,并且我已经在某个地方读到了我们可以从文件中获取输入并将输出写入文件而不是使用终端来提供输入的地方。这是我使用 freopen() 完成的,但遇到了问题。
问题是我无法从文件中读取字符串输入 (input.txt) 或写入 C++ 中的输出文件 (output.txt)。但是整数、字符、浮点数的读取,一切都很好,但只有字符串输入有问题。我什至可以使用字符数组输入字符串,效果很好。但有时使用字符数组对程序来说并不是更好。所以,如果有人可以帮助我,我将不胜感激。还有一件事是,当我们尝试接受字符串输入时,程序会执行但什么也没有发生。
这是我的代码以及输入和输出 **ps:**input指执行时input.txt中的数据,output指执行后output.txt中的数据
我的 PC 中的 C++ 版本 - C++14(Mingw 编译器)
```this first code is where problem exists```
#include<iostream>
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string a;
cin>>a;
// here I even tried getline(cin,a) but it also doesn't work as program executes
// but nothing will be written to output
cout<<a<<"\n";
return 0;
}
input - abcdef
output- (BLANK)
----------
#include<iostream>
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a;
cin>>a;
cout<<a;
return 0;
}
input - 9
output- 9
----------
#include<iostream>
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
char a[100];
cin>>a;
cout<<a<<"\n";
return 0;
}
input - abcdefg
output - abcdefg
----------
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string a="abcdef";
cout<<a<<"\n";
return 0;
}
input - (BLANK)
output - (BLANK)
【问题讨论】:
-
我很困惑,您声称使用
freopen()是为了运行得更快,但您的代码仅在不被判断时明确使用它。为什么要打扰? -
我已经在 MSYS2 中包含的 MinGW 下编译了第一个代码:g++.exe(Rev9,由 MSYS2 项目构建)10.2.0 我无法重现您遇到的问题。我在 output.txt 文件中看到“abcdef”输出。
-
我一直想知道
freopenshuffle。为什么不编写使用泛型istream的函数并根据需要传递给这些函数cin或ifstream而不必费力? -
建议:使用开发环境附带的任何调试工具逐步完成程序,并确保
cin>>a;确实阅读了您想要的内容。 -
另一个建议:你不想在比赛期间这样做,因为它会减慢速度,但是当你试图弄清楚为什么事情不工作时,最好的起点是通过始终检查返回码。
freopen中的任何一个都可能失败。你没看。cin>>a;可能失败了。你没看。cout<<a;可能失败了。你没看。结果,您对程序中真正发生的事情几乎一无所知,一切都会出人意料。在生产代码中,如果你可以测试失败而你没有,那你就是个傻瓜。