ing*_*oxd 1 c++ command-line-arguments
昨天我在c ++中创建了一个简单的程序,它使用通过命令行传递的参数.
E.G. myDrive:\myPath\myProgram.exe firstWord secondWord
Run Code Online (Sandbox Code Playgroud)
程序运行良好,并且做了它所拥有的,但我有一点好奇:我必须先编写argc --;才能使用它,否则我有一个运行时崩溃[编译器不会说!].
特别是argc当我运行它时,我没有给程序任何单词作为参数,这给了我一个不错的时间......
现在它有效,所以一点也不差,但我想知道为什么会这样![PS制作argc --;和打印它,它给出0了价值!]
编辑:这里使用的所有的主题 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];
}
}
}
Run Code Online (Sandbox Code Playgroud)
参数包括程序本身的名称,因此argc始终至少为1.
这是典型的循环:
int main(int argc, char * argv[])
{
for (int i = 0; i != argc; ++i)
{
std::cout << "Argument #" << i << ": " << argv[i] << "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以向后打印:
while (argc--)
{
std::cout << argv[argc] << "\n";
}
Run Code Online (Sandbox Code Playgroud)