【发布时间】:2013-06-10 14:51:57
【问题描述】:
#include <iostream>
#include <cstring>
using namespace std;
void reverse(char* sentence)
{
int index = strlen(sentence) - 1;
char last = '\0';
int hold = 0;
while ( index != 0){
while (sentence[index] != ' ')
index--;
hold = index; //keeps the index of whitespace
while (sentence[index] != last){
cout << sentence[index]; //printing till it either hits end character or whitespace.
index++;
}
last = sentence[hold]; //Keeps the whitespace
index = hold; //
}
}
int main()
{
char* sentence = new char[256];
cin.getline(sentence, 256);
reverse(sentence);
}
我想颠倒一个句子中的单词顺序,你可以在上面看到我的尝试。
示例输入和输出应该是这样的:
Howdy Mr. Mcfly?
Mcfly? Mr. Howdy
我在哪里得到:
Howdy Mr. Mcfly?
Mcfly?
互联网上有很多类似的问题,但我想要的是在我自己的代码中找到错误。
【问题讨论】:
-
如果您使用 C++,为什么要使用 char*?使用字符串会容易得多。我注意到您标记为“动态数组”是否有某些特定原因您使用 char* 会导致无法接受切换到使用字符串的答案?
-
当您通过调试器运行示例时会看到什么?
-
现在是开始学习如何使用调试器的好时机。通过单步执行代码并检查变量,您应该能够很快找到自己的错误。
-
是的,我知道使用字符串和其他方式会更容易,但我只是作为初学者练习。
-
将每个单词添加到堆栈并开始弹出那些傻瓜