输入输出练习--如何处理字符串输入的空格
分析:我的想法是用cin加循环来屏蔽掉输入过程中的空格,于是写出了以下代码:
1 #include "iostream" 2 #include3 #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 ) 21 { 22 if(i 1) 23 cout< " "; 24 else 25 26 cout< endl; 27 } 28 } 29 }
但是,却是不通过的。
下面是别人的代码:
1 #include2 #include 3 #include 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 1;i++) 16 cout< " "; 17 cout< 1]< //保持输出格式,这里要注意 18 str.clear(); 19 } 20 } 21 22 return 0; 23 }
结论:对cin的输入输出理解待加强,应该是每一行的测试用例最后一个字符是 ‘\n’,而不是自己想当然用cin>>s就能够处理得了的。