注意点
- 用getline输入字符串前,记得吸收回车(getline相关参考:https://blog.csdn.net/qq_45700494/article/details/111560695?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-0&spm=1001.2101.3001.4242)
- 测试数据五运行时间过长,翻了群聊天记录,添加ios::sync_with_stdio(false);解决
【问题描述】
给出一个字符串,请将其每个单词反转后输出。
【输入形式】
输入第一行为一个正整数N,表示测试用例数,接下来的N行,每行一个字符串。
【输出形式】
输出N行,每行对应一个反转后的字符串。
#include<iostream>
#include<sstream>
using namespace std;
void reverse(string& s)
{
char* p=&s[0];char* q=&s[s.length()-1];
while(p<q)
{
char temp;
temp=*q; *q=*p; *p=temp;
p++;q--;
}
}
int main()
{
ios::sync_with_stdio(false);
int n;cin>>n;cin.get();
for(int time=0;time<n;time++)
{
string str,s,temp;
getline(cin,str);
stringstream in(str);
while(in>>temp)
{
reverse(temp);
s+=temp+" ";
}
cout<<s<<endl;
}
}
灵异事件
以下为舍友的代码
在我的电脑上提交这份代码数据五会运行时间过长,不知道为什么在舍友的电脑上提交全部正确
亲眼所见,通想无。
#include<iostream>
#include<sstream>
#include<algorithm>
using namespace std;
int main(){
int n;
cin>>n;
cin.get();//换行时用
while(n--){
string s;
//cin.get();此处又没有换行
getline(cin,s);
stringstream ss(s);
//ss.str(s);//
while(ss>>s){//按空格读取string
reverse(s.begin(),s.end());
cout<<s<<" ";
}
cout<<endl;
}
}