命令行参数是一些字符串吗? [英] Are command line arguments some strings?

查看:386
本文介绍了命令行参数是一些字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在几个小时前就在C ++中提出了一个关于命令行参数的类似问题。现在我有另一个问题,据我所知,命令行参数将被保存为argv数组中的字符串。所以比较主题与字符串应该是逻辑的,但它不工作在我想要的方式,看看这个代码:

  #include< iostream> 
using namespace std;

int main(int argc,char ** argv)
{
if(argv [2] ==stack)cout< 对;
cout<< argv [2];
return 0;
}



现在我将此命令传递给我编译的应用程序zero.exe; p>

  zero.exe堆栈

输出应为rightstack,但如果命令将跳过,只有 cout < argv [2]; 将执行,因此只有堆栈将显示在监视器上。它显示stack被保存到 argv [2] ,因此 if(argv [ 2] ==stack)应该工作,但它不是。

由于历史的原因,参数被传递为C风格的字符串。也就是说,每个都是一个指向字符数组的指针,用零值字符标记结束。同样,一个字符串字面量(如stack)是一个简单的字符数组。



指针,即使字符串值相等也不会相等。要比较字符串,可以将一个(或两者)转换为 std :: string

  #include< string> 

std :: string arg2(argv [2]);
if(arg2 ==stack)std :: cout<< right\\\
;

或使用C库函数比较C风格字符串;这可能更有效,但也更难阅读:

  #include< cstring> 

if(std :: strcmp(argv [2],stack)== 0)std :: cout< right\\\
;

此外,参数从1计数,程序名称为 argv [0] ,因此您可能想要测试 argv [1] ,而不是 argv [2]


I have asked a similar question about command line arguments in C++ some hours ago. Now I have another problem, as far as I know, command line arguments will be saved like a string in argv array. so comparing theme with a string should be logical, but it does not work in the way I want, look at this code:

#include <iostream>
using namespace std;

int main(int argc,char** argv)
{
    if (argv[2]=="stack") cout << "right";
    cout << argv[2];
    return 0;
}

now I pass this command to my compiled application named zero.exe;

zero.exe stack

the output should be "rightstack", but if command will skip and only cout << argv[2]; will execute, so only stack will be shown on monitor. it shows "stack" is saved into argv[2], so if (argv[2]=="stack") should work, but it is not. where is the problem?

解决方案

For historical reasons, the arguments are passed as C-style strings; that is, each is a pointer to an array of characters, with a zero-valued character to mark the end. Similarly, a string literal (like "stack") is a simple array of characters.

Your code compares two pointers, which will not be equal even if the string values are equal. To compare the strings, either convert one (or both) to std::string:

#include <string>

std::string arg2(argv[2]);
if (arg2=="stack") std::cout << "right\n";

or use the C library function for comparing C-style strings; this might be more efficient, but is also harder to read:

#include <cstring>

if (std::strcmp(argv[2], "stack") == 0) std::cout << "right\n";

Also, the arguments are counted from 1, with the program name as argv[0], so you probably want to be testing argv[1] rather than argv[2].

这篇关于命令行参数是一些字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆