如何在 Cygwin 中运行多个参数
我一直在尝试运行一个程序,该程序将反转字符串的顺序并运行它,我必须在提示符中键入第二个参数。
int main(int argc, char* argv[])
{
string text = argv[2];
for (int num=text.size(); num>0; num--)
{
cout << text.at(num);
}
return 0;
}
例如 ./program lorem 结果:merol
I've been trying to run a program that will invert the order of a string and to run it, I have to type a second argument in prompt.
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 result: merol
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您遇到异常是因为
num
超出范围。size()
返回一个比字符串中最大有效索引大一的值,因此at()
抛出异常。I think you're getting an exception because
num
is out of bounds.size()
is returning a value one larger than the biggest valid index into the string, soat()
is throwing an exception.您错过了包含并错误地使用了
string::at
。字符串中有size()
字符,但从 0 开始计数。然后循环必须运行到 num >= 0 而不是 num > 为止。 0. 您还在argv
中使用了错误的索引。这仍然是 C++ 的令人厌恶的事情。更清晰的方法是:
You missed the includes and used
string::at
wrong. There aresize()
chars in the string but you start counting at 0. Then the loop has to run until num >= 0 and not num > 0. You also used the wrong index intoargv
.This would still be an abomination of C++. A clearer way would be: