在进行写题时,往往会遇到多行输入问题,因此在这里进行一些方法总结,下面以C语言和java为例分别演示
C语言
输入
简单的数据输入:
#include<stdio.h>
int main()
{
int a,b;
while (scanf("%d%d",&a,&b) != EOF)// 一律用这种写法,把你的scanf函数写成这样子,除了return 0之外,其他的语句都要用大括号括起来
{
printf("%d\n",a+b);
}
return 0;
}
指定数据量
有时会在数据的第一行提供数据量大小,比如第一行是100,则表示有100组数据。参考代码:
#include
int main(void)
{
int n, a, b;
scanf("%d", &n);
while (n--)
{
scanf("%d %d", &a, &b);
printf("%d\n", a + b);
}
return 0;
}
以特定元素作结束符
这种输入和第一种类似。常见的是规定以0作为结束符。
参考代码:
#include
int main(void)
{
int a, b;
while (scanf("%d %d", &a, &b), a || b)
printf("%d\n", a + b);
return 0;
}
字符串输入
~scanf方式
char str[10][10];//定义二维数组,保存多个字符串
int i = 0;
while (~scanf("%s", str[i]))
{
i++;
}
EOF方式
char str[10][10];//定义二维数组,保存多个字符串
int i = 0;
while (scanf("%s", str[i])!=EOF)
{
i++;
}
根据输入元素的个数
char str[10][10];//定义二维数组,保存多个字符串
int i = 0;
while (scanf("%s", str[i])==1)//表示输入一个元素时,循环进行
{
i++;
}
补充:
使用
scanf("%[^\n]", str[i]);
输入方式可以实现整行的输入,但仍然无法实现多行不确定数的输入,在java中可以借助其特有的函数实现这一输入
输出
输出格式统一
这种比较简单,只要按要求来就没问题的。比如每组输出占一行,或者每组输出后面加一个空行。比如1000题。
数据之间有空行
(1)对于这种输出,有时候还会告诉你有几组输入,这样你就可以自己判断一下是不是最后一组。是就不输出空行,否则多输出一个空行。而有时候连共有几组数据都不会告诉你。其实不论知不知道有几组数据,我们都可以这样处理。
(2)第一组数据后面不加空行。 第二组开始,每组前面加空行。参考代码:
#include
int main(void)
{
int a, b, i = 0;
while (scanf("%d %d", &a, &b), a || b)
printf((i++? "\n%d\n": "%d\n"), a + b);
return 0;
}
java
已知长度输入
public class test_0806_1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int lent = input.nextInt();
int[] arr = new int[lent];
for (int i = 0; i < lent; i++) {
arr[i] = input.nextInt();
}
for (int k : arr) {
System.out.print(k + " ");
}
}
}
已知行数输入
public class test_0806_2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t_length = input.nextInt();
String[] aa = new String[t_length];
input.nextLine();
for (int i = 0; i < t_length; i++) {
aa[i] = input.nextLine();
}
for (String str1 : aa) {
System.out.println(str1);
}
}
}
不定行数输入
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String str = scanner.nextLine();
//借助split函数以空格为界限分割
String[] str1 = str.split(" ");
int N = str1.length;
double[] num = new double[N];
for (int i = 0; i < N; i++) {
num[i] = Double.parseDouble(str1[i]);
}
}
}
}