输入输出练习--如何处理字符串输入的空格
分析:我的想法是用cin加循环来屏蔽掉输入过程中的空格,于是写出了以下代码:
1 #include "iostream" 2 #include <vector> 3 #include "algorithm" 4 using namespace std; 5 int main() 6 { 7 8 string s; 9 int n=0; 10 while(cin>>n) 11 { 12 vector<string> temp; 13 while(cin>>s) 14 { 15 16 temp.push_back(s); 17 18 } 19 sort(temp.begin(),temp.end()); 20 for(int i=0;i<temp.size();i++) 21 { 22 if(i<temp.size()-1) 23 cout<<temp[i]<<" "; 24 else 25 26 cout<<temp[i]<<endl; 27 } 28 } 29 }
但是,却是不通过的。
下面是别人的代码:
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 5 using namespace std; 6 7 int main(){ 8 string s; 9 vector<string> str; 10 while(cin>>s){ 11 str.push_back(s); 12 13 if(cin.get()=='\n'){ 14 sort(str.begin(),str.end()); //库函数,实现排序功能,需包含头文件“algorithm” 15 for(int i=0;i<str.size()-1;i++) 16 cout<<str[i]<<" "; 17 cout<<str[str.size()-1]<<endl; //保持输出格式,这里要注意 18 str.clear(); 19 } 20 } 21 22 return 0; 23 }
结论:对cin的输入输出理解待加强,应该是每一行的测试用例最后一个字符是 ‘\n’,而不是自己想当然用cin>>s就能够处理得了的。
主要为了自己学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术