C、C++ 标准输入重定向 & 万能头 - 编程技巧
转眼到了毕业季,大家都在忙着找暑期实习;我也投了一个,是阿里巴巴的暑期实习;实习,少不了机试,又想起了大一时曾经凑过acm的热闹;当时学到一个技巧,是使用重定向向输入输出函数,这样在进行测试的时候就比较方便了;
这样调试的时候,不用从控制台进行手动输入,直接从文件中进行输入就行;这样也方便debug;
引入头文件:
#include <cstdio>
经典使用样例:(我一般只重定向输入,还是在标准输出中输出)
freopen("in.txt","r",stdin); freopen("out.txt","w",stdout);
函数解释:(可以使用 man freopen 进行查询)
#include <stdio.h> FILE * freopen(const char *path, const char *mode, FILE *stream);
The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the fopen() function. If the path argument is NULL, freopen() attempts to re-open the file associated with stream with a new mode. The new mode must be compatible with the mode that the stream was originally opened with: Streams open for reading can only be re-opened for reading, streams open for writing can only be re-opened for writing, and streams open for reading and writing can be re-opened in any mode. The ``x'' mode option is not meaningful in this context. The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout).
另外一个技巧就是,c++的万能头:
#include<bits/stdc++.h>
部分平台,不支持此头文件;经过我的测试,macos 的clang++ 11.0.0 好像不支持这个文件;但是g++ 9.3.0通过我的测试,好像支持这个文件;
2021年3月9日 16点19分:
常用编译命令参考:使用 c++ 11 标准;
c++ -std=c++11 example.cc -o example ; ./example
参考代码:
#include <cstdio> #include <iostream> int main(){ freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); // 使用w模式,每次打开文件都清空内容; std::string buffer; while (std::cin >> buffer) { std::cout << buffer << " "; } std::cout << std::endl; return 0; }
保持更新,转载请注明出处;更多内容请关注cnblogs.com/xuyaowen;
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 为什么说方法的参数最好不要超过4个?
· C#.Net 筑基-优雅 LINQ 的查询艺术
· 一个自认为理想主义者的程序员,写了5年公众号、博客的初衷
· 大数据高并发核心场景实战,数据持久化之冷热分离
· 运维排查 | SaltStack 远程命令执行中文乱码问题
· 博客园众包平台:诚征3D影像景深延拓实时处理方案(预算8-15万)
· 为什么说方法的参数最好不要超过4个?
· 发布一个小功能,通过 markdown 图片语法嵌入B站视频
· 《HelloGitHub》第 111 期
· Spring AI Alibaba 1.0 正式发布!核心特性速览+老项目升级指南
2019-03-20 fedora 28/29 配置 C++ 环境