我一直在尝试运行一个程序来反转字符串的顺序并运行它,我必须在提示符下键入第二个参数。
int main(int argc, char* argv[])
{
string text = argv[2];
for (int num=text.size(); num>0; num--)
{
cout << text.at(num);
}
return 0;
}
e.g。 ./ program lorem 结果: merol
答案 0 :(得分:4)
#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&gt; = 0而不是num&gt;你还在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;
}
答案 1 :(得分:1)
我认为你得到了一个例外,因为num
超出范围。 size()
在字符串中返回一个大于最大有效索引的值,因此at()
会抛出异常。