OJ读取输入样例

在OJ、牛客网上,经常有在线编程题需要读取输入样例,另外可能还需要一定的格式化输出知识,之前一直不太会这方面,此处来汇总一下。

python版

python的比较简单,可以直接通过input()语句读取一整行内容,并返回str类型。具体使用如下:

1
2
3
4
5
6
7
8
9
10
11
12
>>> a = input("input:")
input:123
>>> a
'123'
>>> type(a)
<class 'str'>
>>> a = int(input("input:"))
input:123
>>> a
123
>>> type(a)
<class 'int'>

如果一行有多个数字,则会得到类似'1 2 3'的字符串,可以使用split()分解成单个字符,接下来就可以给返回list,或用map函数处理。如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#eg.1
>>> a = input("input:").split()
input:1 2 3 4
>>> a
['1', '2', '3', '4']
#eg.2
>>> a = [int(i) for i in input("input:").split()]
input:1 2 3 4
>>> a
[1, 2, 3, 4]
#eg.3
>>> n, m = map(int, input().split())
1 2
>>> n
1
>>> m
2

C++版

C++ 通常使用cin函数读取数据,通常用到的方法有cin>>,cin.get,cin.getline。cin函数在std命名空间中。

cin>>

  1. cin>>等价于cin.operator>>(),即调用成员函数operator>>()进行读取数据。
  2. cin>>会忽略空格、tab或换行这些分隔符,并继续读取下一个字符。

scanf

scanf函数原型在头文件“stdio.h”,是C语言风格的通用终端格式化输入函数。

其调用格式为: scanf(“<格式化字符串>”,<地址表>); 例如:scanf("%d %d",&a,&b);

格式化输入输出

格式字符 说明
%a 读入一个浮点值(仅C99有效)
%A 同上
%c 读入一个字符
%d 读入十进制整数
%i 读入十进制,八进制,十六进制整数
%o 读入八进制整数
%x 读入十六进制整数
%X 同上
%s 读入一个字符串
%f 读入一个浮点数
%F 同上
%e 同上
%E 同上
%g 同上
%G 同上
%p 读入一个指针
%u 读入一个无符号十进制整数
%n 至此已读入值的等价字符数
%[] 扫描字符集合
%% 读%符号

特殊格式

printf("%4d",n);//这个4是指输出的空间为4
printf("%.2f",n);

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
#include<stdio.h>
int main(){
double n=12.3456;
int n1=123456;
printf("The format of %%8d%%c is: ");
printf("%8d%c",n1,'\n');//这个4是指输出的空间为4
printf("The format of %%.2f%%c is: ");
printf("%.2f%c",n,'\n');
return 0;
}

输出为:

1
2
The format of %8d%c is: 123456
The format of %.2f%c is: 12.35

循环处理

对于传统OJ一次处理多个case,所以代码需要循环处理,一般通过while循环来出来多个case。

C

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#include <string.h>//strlen在此库中
int main() {
int a;
char b[1000];
while(scanf("%d %s",&a, b) != EOF)//注意while处理多个case
//b为字符数组,b即代表指向数组开头的指针,因此不用&b
printf("%d%d%s\n",a,strlen(b),b);
return 0;
}

C++

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>
using namespace std;
int main() {
int a,b;
string s;
while(cin >> a >> b >> s)//注意while处理多个case
cout << a+b << s << endl;
}

python

1
2
3
4
5
6
7
8
9
10
11
12
13
# eg.1
import sys
for line in sys.stdin:
a = line.split()
print(int(a[0]) + int(a[1]))
# eg.2
while(True):
try:
a=input()
print(a)
except:
break

上面这些内容就足够应付OJ系统了,如果还想了解更多cin函数内容,可参考Dablelv的博客专栏

本文标题:OJ读取输入样例

文章作者:微石

发布时间:2018年06月04日 - 21:06

最后更新:2018年07月24日 - 09:07

原始链接:akihoo.github.io/posts/5ad569e3.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。