#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string text = argv[1];
for (int num=text.size() - 1; num >= 0; num--)
{
cout << text.at(num);
}
return 0;
}
您錯過了包含並使用了string::at
錯誤。字符串中有size()
個字符,但您從0開始計數。然後循環必須運行,直到num> = 0並且不是num> 0。您還在argv
中使用了錯誤的索引。
這仍然是C++的憎惡。更清晰的方式是:
#include <iostream>
#include <string>
#include <algorithm>
int main(int argc, char* argv[])
{
std::string text = argv[1];
for(std::string::reverse_iterator it = text.rbegin(); it != text.rend(); ++it) {
std::cout << *it;
}
std::cout << std::endl;
//or if you want further usage of the reversed string
std::reverse(text.begin(), text.end());
std::cout << text;
return 0;
}
來源
2010-06-14 17:55:47
pmr
那麼,你有什麼試過,沒有奏效? – 2010-06-14 17:41:06
從C到C++重新標記 – 2010-06-14 17:44:05
下面是關於C命令行參數的一個很好的小教程:http://www.cprogramming.com/tutorial/c/lesson14.html – 2010-06-14 17:44:53