簡體   English   中英

在C ++中將參數與整數進行比較

[英]Comparing an Argument with an Integer in C++

我正在使用命令行參數,並且一直在嘗試在參數編號和輸入之間進行比較。 因此,如果有人輸入1,則輸出將為“難度級別為1”。

#include <iostream>
#include <cstring>
using namespace std;
int main(ijnt argc, char* argv[])
{
int a; 
if (argc[1] == '1')
    {
    cout << "The difficulty level is " << argv[1] << endl;
    return 1;
    }
}

我將比較1設為一個字符,但出現錯誤“ ISO C ++禁止在指針和整數[-fpermissive]之間進行比較”,並說該錯誤是

if (argv[1] == '1')

如何獲得與之比較的1作為字符被接受?

argv是字符數組的數組...

因此,請使用strcmp進行比較,或者更好地將其轉換為std::string並進行比較...,但還要確保argc大於1。示例:

#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char* argv[])
{
int a; 
if (argc > 1 && strcmp(argv[1], "1") == 0)
    {
    cout << "The difficulty level is " << argv[1] << endl;
    return 1;
    }
}

要么

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
int a; 
if (argc > 1 && string(argv[1]) == "1")
    {
    cout << "The difficulty level is " << argv[1] << endl;
    return 1;
    }
}

我認為您要的是if (*argv[1] == '1')

命令行參數是字符數組,因此您需要使用std::strcmp()之類的東西來進行比較,如下所示:

int main(int argc, char* argv[])
{
    // check argument exists ...

    if(!std::strcmp(argv[1], "1")) // 0 when equal
    {
        // they are the same here
    }

    // ...
}

從arg中創建一個`std :: string可能更簡單

    if(std::string(argv[1]) == "1")
    {
        // they are the same here
    }

在所有情況下,請確保您檢查參數是否存在:

int main(int argc, char* argv[])
{
    if(!argv[1]) // argument not present (null terminated array)
    {
         std::cerr << "Expected an argument." << std::endl;
         return EXIT_FAILURE;
    }

    // process arg here

    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM