指针与整数的比较

时间:2018-09-20 02:51:45

标签: c++

#include<fstream>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])


for (int i=1; i<argc ; i++)

{
    cout<< argv[i]<< endl;

if( argv[i] == 'all')
         cout<<"hey"<< endl;


}

我正在通过命令文件传递“ 1 all emptyfile”。但是我想比较当争论[i]等于所有人时,我希望它打印出来嘿 无论如何,我都会在if(argv [i] =='all')处收到此错误“指针与整数('char *'和'int')的比较”,我可以做到吗?

2 个答案:

答案 0 :(得分:3)

无法直接比较C风格的字符串,更糟糕的是,'all'不是字符串(您可能是指"all",请注意引号)。

比较它们的C方法是使用strcmp

#include <cstring>

if (std::strcmp(argv[i], "all") == 0) { ... }

答案 1 :(得分:0)

由于使用的是C ++,因此可以使用python3,它可以直接比较字符串。

library(reticulate)

packageVersion("reticulate")
# [1] ‘1.10.0.9002’

use_python(python = "/usr/bin/python", required = TRUE)

py_config()
# python:         /usr/bin/python
# libpython:      /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so
# pythonhome:     /usr:/usr
# version:        2.7.15rc1 (default, Apr 15 2018, 21:51:34)  [GCC 7.3.0]
# numpy:          /usr/lib/python2.7/dist-packages/numpy
# numpy_version:  1.13.3
#
# NOTE: Python version was forced by use_python function

Sys.which("python3")
# python3 
# "/usr/bin/python3" 

use_python(python = "/usr/bin/python3", required = TRUE)

py_config()
# python:         /usr/bin/python
# libpython:      /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so
# pythonhome:     /usr:/usr
# version:        2.7.15rc1 (default, Apr 15 2018, 21:51:34)  [GCC 7.3.0]
# numpy:          /usr/lib/python2.7/dist-packages/numpy
# numpy_version:  1.13.3
# 
# NOTE: Python version was forced by use_python function

注意:std::string用双引号引起来。

运行程序时的输出:

#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
    string s = "all";
    for (int i=1; i<argc ; i++)
    {
        cout<< argv[i]<< endl;      
        if( argv[i] == s)
             cout<<"hey"<< endl;
    }
}