机试ACM模式C++

机试ACM模式C++
9⽉8号华为机试,做题时发现和平时在leetcode上刷题的模式完全不⼀样,结果⼀道都没调试成功,第⼀题⼆叉树遍历放leetcode上应该是直接秒的。写出⼀道就能过啊,真的哭了 T T
简单总结⼀下C++ ACM模式中常⽤的输⼊输出语句,避免以后再出现这种情况。
cin>>x
读取数字或字符串到x变量。会跳过数字/字符串前的space/tab/enter,直到遇到space/tab/enter为⽌(这次遇到的不会跳过,留给下⼀次cin处理)。
getline()
需要 #include <string>
读⼊⼀⾏,最后的enter也会读取,但是会在读⼊的字符串中舍弃enter字符
getline(istream is, string str, 结束符) ,结束符默认是换⾏符 ‘\n’
如果先cin再getline则需要注意cin留下来的enter字符,可以⽤()来取出该enter字符。⽐如输出每
⼀⾏数据的总和:
#include<iostream>
using namespace std;
int main(){
粮食int sum =0;
int temp;高中班级宠物女孩小诗
while(cin >> temp){
sum += temp;
()=='\n'){
cout << sum << endl;
sum =0;
}
}
}
有时候会遇到逗号分隔的情况,对于整数,可以⽤()来跳过逗号
输⼊
1,2,3,4
5,6,7,8
代码
结晶紫vector<int> w;
int temp;
while(cin >> temp){
w.push_back(temp);
()=='\n')break;
}
对于逗号分隔字符串,则需要配合istringstream和getline。⽐如读取若⼲⾏逗号分隔的字符串
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
string line;
while(getline(cin, line)){
string word;
vector<string> vec;
istringstream iss(line);
while(getline(iss, word,',')){
vec.push_back(word);
}
sort(vec.begin(), d());
for(int i=0; i<vec.size()-1; i++){
秸秆成型机cout<<vec[i]<<',';
}
cout<<vec.back()<<endl;
}电工技术论坛
return0;
}
长镜头理论循环输⼊
测试⽤例有时候会放在⼀个⽂件中,所以可能会需要⼀个⼤的循环。可能在某些机试⾥会是这样,但是华为机试好像是单个测试⽤例分开的。如果加了⼤循环,那么像循环⾥⾯使⽤的vector,map什么的⼀定要清空clear()。

本文发布于:2024-09-20 22:37:32,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/470952.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:字符串   机试   逗号   分隔   需要   循环   字符   遇到
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议