算法笔试一般有两种提醒,一种是直接在函数参数中给出要处理的数据,然后通过返回值返回结果。
另外一种是通过输入给出要处理的数据,通过输出给出结果。
所以有必要掌握常用语言的输入输出,下面介绍4中常用语言的输入输出(Java,C,C++,Python)
在介绍各种语言的输入输出前,可以先来看一下算法笔试中题目的输入输出一般分为几种
1. 单个元素的输入(单个字符串,单个数字,单行)
2. 多个元素的输入(多个字符串,多个数字,多行)
2.1 知道输入的元素个数
2.2 不知道输入的元素个数,但是知道输入终止规则(例如,最后一行数据不以逗号结尾)
Java的输入输出,Java的标准输入输出一般要用到Scanner,当通过new Scanner(System.in)创建一个Scanner,控制台会一直等待输入,直到回车结束,把所有输入的内容传给Scanner,作为扫描对象,如果需要获取输入的内容,则只需要调用Scanner的相关方法。
1. 单字符串输入(只截取空格前字符)
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println(str);
2. 单数字输入
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
3. 单行输入
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
4. 多行输入(知道行数)
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
List<String> inputLines = new ArrayList<String>();
for(int i = 0;i < N;i++){
inputLines.add(sc.nextLine());
}
return inputLines;
5. 多行输入(知道输入终止规则,不以逗号结尾)
Scanner sc = new Scanner(System.in);
List<String> inputLines = new ArrayList<String>();
while(sc.hasNextLine()){
inputLines.add(sc.nextLine());
if(!sc.nextLine().endsWith(“,")){
inputLines.add(sc.nextLine());
break;
}
}
return inputLines;
一般来说,使用nextLine()方法就够了,然后结合parse一类的方法,将输入转换成相应的类型,在进行下面的处理。
基于Python的输入输出
Python的输入一般要用到input()函数
1. 输入多行数据,行数已知
N = input()
data = []
for i in range(int(N)):
line = input()
data.append(line)
print(data)
2. 输入多行数据,输入终止规则已知
data = []
while(True):
line = input()
data.append(line)
if(line.endswith(',')):
break
print(data)
可以看出来,Python的输入输出还是蛮简单的。
基于C语言的输入输出,
1. 输入字符串
char str[20];
// gets(str);
// puts(str);
scanf("%s",str);
printf("%s\n",str);
2. 输入数字
int a;
scanf("%d",&a);
printf("%d\n",a);
有些情况下,输入是字符串,因此需要判断字符串是不是数字
//检测一个字符串是否为数字
int check_number(char str[]){
int i = 0;
while (str[i]!='\0'){
if((str[i]>'9'||str[i]<'0')&&str[i]!='.'){
break;
}
i++;
}
return str[i]=='\0'&&i!=0;
}
3. 输入多行数据,行数已知
int a[10];
int i;
int N = 3;
for(i = 0;i < N;i++){
scanf("%d",&a[i]);
}
for(i = 0;i< N;i++){
printf("%d,",a[i]);
}
4. 输入多行数据,输入终止规则已知
基于C++的输入输出
1. 输入单个数字
int data;
cin >> data;
cout << data << endl;
2. 输入单个字符串
char data[30];
cin >> data;
cout << data << endl;
3. 输入多行数据,
4. 输入多行数据,以ctrl+Z终止
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
int num;
vector <int>nums;
while(cin>>num)
{
nums.push_back(num);
}
vector<int>::iterator it;
for(it=nums.begin();it!=nums.end();it++)
{
cout<<(*it)<<endl;
}
return 0;
}