输入输出练习--如何处理字符串输入的空格

分析:我的想法是用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就能够处理得了的。

 

posted @   技术笔记记录  阅读(82)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示