在控制台的一个简单应用程序上,我无法读取参数
int main(int argc, char ** argv) {
if (argc > 1)
strcpy(path, argv[1]);
printf("arguments %dn", argc);
....
argc始终为1
从控制台运行应用程序,如下所示:
open mytestconsoleapp --args arg1 arg2 arg3
argc始终为1。这对我来说很奇怪。
我不明白为什么,怎么了?
如果您实际编写的是C++
而不是C
,则可以使用它。
static std::string path;
int main( int argc, char* argv[ ] ) {
// With either solution you should make sure that the passed in
// argument isn't gigantic.
if ( argc > 1 ) {
path.assign( argv[ 1 ] );
std::cout << path << 'n'
}
// Or you could use one of the std::string constructors.
// This is a nice solution if you don't require global state.
if ( argc > 1 ) {
std::string buffer{ argv[ 1 ] };
std::cout << buffer << 'n';
}
}
如果你在C
中这样做,那么使用:
static char path[ 256 ];
int main( int argc, char* argv[ ] ) {
if ( argc > 1 ) {
strncpy( path, argv[ 1 ], sizeof( path ) - 1 );
printf( "%sn", path );
}
// Or if you don't need the global variable.
if ( argv > 1 ) {
char buffer[ 256 ] = { 0 };
strncpy( buffer, argv[ 1 ], sizeof( buffer ) - 1 );
printf( "%sn", buffer );
}
}
然后使用以下命令运行您的应用程序:./mytestconsoleapp test
行为是正确的。你的程序没有任何问题。但是,%d
是十进制的格式字符串。
我建议你试试%s
?