牛客的ACM格式,需要自己定义输入输出,对leetcode上只刷核心算法的人,需要一定时间入门,整理常用的输入输出,以备不时之需。
单个字符/数字输入
例题1
如题:HJ1 字符串最后一个单词的长度
输入:
hello nowcoder I am robot
输入的代码:
VERSION01:
string s;
getline(cin,s); // s = "hello nowcoder I am robot"
VERSION02:
vector<string> vec;
string word;
while(getline(cin, word, ' ')){
vec.push_back(word);
} //vec = {{hello},{nowcoder},{I},{am},{robot}}
VERSION03:
string s;
cin >> s; //错误,因为cin会在空格处断开,s = "hello"
多个字符/数字输入
例题2
如题:HJ14 字符串排序
输入:
输入的代码:
vector<string> s;
int total;
cin >> total;
string word;
for(int i =0; i < total; i++){
cin >> word;
s.push_back(word);
}
输出的代码:
for(int i =0; i < total; i++){
cout << s[i] << endl;
}
ATTENTION: 起初我是想用getline(),但是有一些问题。
例题3
如题:HJ8 合并表记录
输入:
输入的代码:
int total;
cin >> total;
for(int i = 0; i < total; i++){
int a, b;
cin >> a >> b;
}