-2

您好,如果输入“./prog7x hello there”作为命令行参数,我正在制作一个程序来显示以下内容:

argument 0 is "./prog7x", has length 8, contains 5 alphabetic characters 
argument 1 is "hello", has length 5, contains 5 alphabetic characters 
argument 2 is "there", has length 5, contains 5 alphabetic characters 
Total length 18: ./prog7xhellothere 

我在计算字母字符时遇到了麻烦。我有一个函数来获取长度,但我不明白如何在长度完成后显示字符的计数。这是到目前为止的程序......我只编码了几个月,所以任何建议都值得赞赏!

#include <cctype> //isalpha
#include <cstdio> 
#include <cstring> //strlen
#include <cstdlib>

//Function to display what argument we're on
void displayArgument(char* arr1[],int num);

//Funtcion to get the length of a command line argument then,
//display number of alphabetical characters it contains
void displayLength(char* arr[],int length);

//Function to count the total length, concatenate together,
//and display results
//void displayTotalCat(char* arr2[],int total);

int main(int argc, char* argv[])
{      
    displayArgument(argv,argc);
    displayLength(argv,argc);


    return 0;
}

//Function to display what argument we're on
void displayArgument(char* arr1[],int num)
{
  for(int i=0; i<num; i++) {
       printf("Argument %d is ",i); //what argument we're on
       printf("'%s'\n",arr1[i]);
      } 
}

//Funtcion to get the length of a command line argument then,
//display number of alphabetical characters it contains
void displayLength(char* arr[],int length)
{
  for (int l=0; l<length; l++) {        //what length that position is
       int len=strlen(arr[l]); //what is the length of position l
       printf("Length is %d,\n",len);   //print length
    for(int j=0; j< len ;j++) {
      int atoi(strlen(arr[l][j]));
      printf("Contains %d alphabetical characters",arr[l][j]);
     }
    }

}

//Function to count the total length, concatenate together,
//and display results
//void displayTotalCat(char* arr2[],int total)
4

1 回答 1

0

如果您只想要结果,请跳到最后,但让我们一起来看看。这是您的代码有问题的部分:

for(int j=0; j< len ;j++) {
    int atoi(strlen(arr[l][j]));
    printf("Contains %d alphabetical characters",arr[l][j]);
}

目前,您正在循环内打印。所以让我们把那部分拉出来:

for(int j=0; j< len ;j++) {
  int atoi(strlen(arr[l][j]));
 }
 printf("Contains %d alphabetical characters",arr[l][j]);

伟大的。此外,我们不能再arr[l][j]在循环之外打印(j超出范围),因此我们需要预先声明某种变量。这对于帮助我们计数也很有意义,因为当我们确定一个字符是字母数字时,我们会想要添加到这个变量中:

int alphas = 0;
for(int j = 0; j < len; j++) {
    if(????){
        alphas = alphas + 1;
    }
}
printf("Contains %d alphabetical characters", alphas);

请注意,我还稍微格式化了您的代码。一般来说,程序员遵循关于空格、缩进、命名等的规则,以使他们的代码更容易被其他人阅读。那么,我们如何判断一个字符是否是字母数字呢?我们可以使用一系列 if 语句(例如if(arr[l][j] == '1')等),但这不是很聪明。你调查是对的isalpha!首先,将其添加到文件的顶部:

#include <ctype.h>

然后,您应该能够isalpha像这样调用该函数:

int alphas = 0;
for(int j = 0; j < len; j++) {
    if(isalpha(arr[l][j])){
        alphas = alphas + 1;
    }
}
printf("Contains %d alphabetical characters", alphas);
于 2016-11-17T01:34:50.047 回答