笔试中输入输出的处理--简易
笔试中输入输出的处理
随便写写,不喜勿喷
首先是java的处理
第一步:引入输入流,同时引包
import java.io.*;//这里io.*方便
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
抛出异常
由于reader.readLine()会抛出异常,为了简单直接抛出 throw Exception
读取单行
//可以处理下面的样例
//1. 不知道长度的数组,以空格分割,下一行为sample
//1 2 3 4 5
String line = reader.readLine();
String[] sp = line.split(" ");
int[] arr = new int[sp.length];
for(int i = 0;i < sp.length;sp++) {
arr = Integer.parseInt(sp[i]);
}
//2. 接收带空格的单行字串
String line = reader.readLine();
读取多个case组
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(reader.readLine());
List<String> l = new ArrayList<>();
while(t-- > 0) {
// 单次处理一个case的过程
String tmp = reader.readLine();
l.add(tmp);
}
c++语法中,上述使用方法替换语法后如下所示。
// 引入输入流
#include<bits/stdc++.h>
using namespace std;
// 读取单行
string s;
cin >> s;
// 不知道长度的数组,以空格分割
string s;
getline(cin, s);
vector<string> v;
split(s, v, " ");
vector<int> a;
for(string str : v) {
a.push_back(stoi(str.c_str()));
}
// 读取多个case
cin >> t;
while(t--) {
// sovle函数为单独处理一次case的过程
sovle();
}
// 注意点,cin 和getline输入结合使用,由于cin不会刷新输入缓冲中的换行符,所以我getchar()手动过滤换行符
cin >> t;
getchar();
getline(cin, s);
// string转int, long, double
int number = stoi(str.c_str());
double number = stod(str.c_str());
long number = stol(str.c_str());
// int,long ,double转string
//to_string方法
// 附上split代码
void split(string& s, vector<string>& v, const string& c) {
string::size_type pos1 = 0, pos2;
while((pos2 = s.find(c, pos1)) != string::npos) {
v.emplace_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
}
if (pos1 != s.length()) {
v.emplace_back(s.substr(pos1));
}
}
小建议
输入输出是笔试中的基础,不要眼高手低,建议多找几种常见的case优化自己的模板。
另外,当输入十分复杂时,学会使用split函数会提高效率
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理