[英]How to process command line arguments?
Yesterday I made a simple program in c++ that uses the arguments passed through command line. 昨天我用c ++编写了一个简单的程序,该程序使用了通过命令行传递的参数。
E.G. myDrive:\myPath\myProgram.exe firstWord secondWord
The program run fine and do what it has to, but there's a little curiosity I have: I had to write argc --;
该程序可以正常运行并执行所需的操作,但是我有一点好奇:我必须写
argc --;
before I could use it well, otherwise I have a run-time crash [The compiler won't speak!]. 在我不能好好使用它之前,否则会发生运行时崩溃[编译器不会讲话!]。
In particular argc
gives me a bad time when I don't give any word as argument to the program when I run it... 特别是当我在运行程序时不给任何单词作为程序的参数时,
argc
给我带来了糟糕的时光...
Now it works, so isn't bad at all, but I wonder why this is happening! 现在它可以工作了,一点也不坏,但是我想知道为什么会这样! [PS making
argc --;
[PS制作
argc --;
and printing it, it gives 0
as value!] 并打印出来,它的值为
0
!]
EDIT: Here all the istructions that use argc
编辑:这里所有使用
argc
的指令
int main(int argc, char *argv[]) {
[...]
argc --;
if(argc > 0){
if(firstArg.find_last_of(".txt") != string::npos){
reading.open(argv[1], ios::binary);
[...]
}
}
if ((!(firstArg.find_last_of(".txt") != string::npos)) && argc > 0){
[...]
for(int i = 1; i <= argc; i ++){
[...]
toTranslate = argv[i][j];
[...]
toTranslate = argv[i][j];
}
}
}
The arguments include the name of the program itself as well, so argc
is always at least 1. 参数还包括程序本身的名称,因此
argc
始终至少为1。
Here's the typical loop: 这是典型的循环:
int main(int argc, char * argv[])
{
for (int i = 0; i != argc; ++i)
{
std::cout << "Argument #" << i << ": " << argv[i] << "\n";
}
}
Alternatively you can print backwards: 或者,您可以向后打印:
while (argc--)
{
std::cout << argv[argc] << "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.