簡體   English   中英

在 C 中,當調用 function 時,如何確定 argv[1] 的長度?

[英]In C, how can I determine the length of argv[1], when calling a function?

我正在嘗試編寫一個程序: 1- 在命令行中必須有 2 個 arguments。 2- 必須調用檢查第二個參數是否為數字的 function。

這是我最好的嘗試:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

bool only_digits(string s[1]);

int main(int argc, string argv[])
{
    // Check how many arguments were typed in the command line.
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    // Check that argv[1] is a digit.
    bool is_digit = only_digits(&argv[1]);
    if (is_digit)
    {
        printf("Usage: ./caesar key\n./caesar ");
        return 1;
    }
    return 0;
}

bool only_digits(string s[1])
{
    for (int i = 0, n = strlen(s[1]); i < n; i++)
    {
        int is_digit = isdigit(s[1][i]);
        if (is_digit == 0)
        {
            return 1;
        }
    }
    return 0;
}

當我運行這個程序並在命令行中提交一個字符串作為第二個參數時,結果是“分段錯誤(核心轉儲)”。 我知道問題是我的 function 中的“s[1]”在末尾不包含 NULL 字符,所以 function' 但是,當我在 main 中包含 function 時,問題就消失了。

int main(int argc, string argv[])
{
    // Check how many arguments were typed in the command line.
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    // Check that argv[1] is a digit.
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        int is_digit = isdigit(argv[1][i]);
        if (is_digit == 0)
        {
        printf("Usage: ./caesar key\n./caesar ");
        return 1;
        }
    }
    return 0;
}

但是因為我需要調用 function,所以我需要幫助:P

function 必須聲明為

bool only_digits(string s);

並稱為

bool is_digit = only_digits(argv[1]);

function的定義可以看如下

bool only_digits( string s )
{
    if ( *s == '\0' ) return false;

    while ( isdigit( ( unsigned char )*s ) ) ++s;

    return *s == '\0';
}

盡管最好聲明 function 而不更改其定義,例如

bool only_digits( const char *s );

我實際上在發布后幾分鍾就解決了我的問題......我只是添加了:

    bool only_digits(string s);    
...
    string argument = argv[1]; // <- this line!
    bool is_digit = only_digits(argument);

當然,我從 function 定義中刪除了“[1]”... :)

暫無
暫無

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

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