我需要一些帮助调试我的代码。该代码旨在逆转以句子形式的字符串中的单词[假设字符串没有"。在最后]。由于某种原因,我将作为输出所获得的是缩进的输出以及第一个单词之后的额外空间以及缩进的输出减去第一个单词。我是编码的初学者;因此,如果可能的话,我会很欣赏更简单的理解解决方案,或使用循环,字符串和数组的解决方案。
样本输入:
My name is Edward
预期输出:
Edward is name My
接收到的输出:
Edward is name
这是我到目前为止的代码:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main() {
string s, n, a;
getline(cin, s);
for (int i = s.length(); i >= 0; i--){
if (s[i] != 32 ) {
n += s[i];
}
else {
for (int j = n.length() -1; j >= 0; j--){
a += n[j];
}
cout << a << ' ';
n.clear();
a.clear();
}
}
cin.ignore();
getchar();
return 0;
}
另外,我只是注意到最后还有一个额外的空间。如果有一种方法可以取消输出最后一个空间;请告诉我。
感谢您的阅读,感谢您的帮助。
如我的评论中所述,您正在按字符逆转整个字符串,但是您需要拆分单词并反向:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s, n;
getline(cin, s);
std::istringstream iss(s);
std::vector<string> words;
while(iss >> n) {
words.push_back(n);
}
std::reverse(words.begin(),words.end());
for(auto word : words) {
std::cout << word << ' ';
}
getchar();
return 0;
}
实时演示
因此,这实际上只是从πάνταῥεῖ的出色答案中抽象的另一个步骤。您可以使用istream_iterator
和ostream_iterator
进一步简化代码。
可以将回答您问题的整个代码归为:
const vector<string> words{ istream_iterator<string>(cin), istream_iterator<string>() };
copy(crbegin(words), crend(words), ostream_iterator<string>(cout, " "));
实时示例
编辑:感谢您的评论和答案的帮助,我解决了额外空间的问题,并在最后添加了一些输出最终单词的东西。它不是完美的,但是可以起作用。:)
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, n;
getline(cin, s);
for (int i = s.length() -1; i >= 0; i--){
if (s[i] != 32) {
n += s[i];
}
else {
for (int j = n.length() -1; j >= 0; j--){
cout << n[j];
}
cout << ' ';
n.clear();
}
}
for (int k = n.length() -1 ; k >= 0; k--)
cout << n[k];
cin.get();
return 0;
}
您可以使用strrev();
功能代替所有for
块。