牛客网&赛码网 输入输出格式 python&C++
Note:
你的程序需要stdin(标准输入)读取输入,然后stdout(标准输出)来打印结果,举个例子,你可以使用c语言的scanf或者c++的cin来读取输入,然后使用c语言的printf或者c++的cout来输出结果。
一次处理多个case,所以代码需要循环处理,一般通过while循环来出来多个case。
C++
以下例子为空格隔开,使用cin、cout读入读出。赛码网与牛客网一致。
1)单行输入
#include<iostream>
using namespace std;
int main(){
int m,n,k;
cin>>m>>n;
cout<<m<<endl;
cout<<n<<endl;
return 1;
}
2)多行输入,每一行是一个测试样例,不确定样例个数,所以用while()循环读取
#include <iostream>
using namespace std;
int main() {
int a,b;
while(cin >> a >> b)//注意while处理多个case
cout << a+b << endl;
}
3)多个测试用例,每个测试用例多行
输入包含多组测试用例。对于每组测试用例:第一行包含两个整数N和M,在接下来的M行内,每行包括3个整数。要求按照输入格式输出。
已知每个测试用例有M组输入,就可以用for(int i = 0; i < M; i++)来读取M组输入。
#include <iostream>
using namespace std;
int main()
{
int N, M;
// 每组第一行是2个整数,N和M,至于为啥用while,因为是多组。
while(cin>> N >> M) {
cout << N << " " << M << endl;
// 循环读取“接下来的M行”
for (int i=0; i<M; i++) {
int a, b, c;
cin >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
}
}
return 0;
}
4) 固定个数&格式的输入,需一次全部读入;固定格式的输出,按照题目要求设计。
输入:getline()
getline每遇到一个行分割符都会返回一次;
getline()函数从输入流中提取字符并将其附加到字符串对象中,直到遇到分隔字符为止;
在执行此操作时,字符串对象str中先前存储的值将被输入字符串(如果有的话)替换。
istream& getline(istream& is,
string& str, char delim);
istream& getline (istream& is, string& str); //an delimitation character is by default new line(\n)character
stringstream: 例如cin,输入流
string:字符串
example:
#include <iostream>
#include <sstream>
using namespace std;
string input = "abc,def,ghi";
istringstream ss(input);
string token;
int main(){
while(getline(ss, token, ',')) {
cout << token << endl;
}
return 0;
}
output:
abc
def
ghi
将input string用istringstream转成input stream,token用于保存每个被“,”分隔开的一个小输入(e.g abc),以string的形式,每次遇到“,”都会停止读取输入并输出token的值。token的值每次从ss中读取都会被覆盖。
Examples:
- 字符串排序(1)
#include<iostream>
#include<vector>
#include<string>
#include <algorithm>
using namespace std;
int main(