функция — c ++ Работа с аргументами командной строки .. isalpha не работает и как объединить вместе

Здравствуйте, я делаю программу для отображения следующего, если в качестве аргумента командной строки было введено «./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)

-2

Решение

Перейдите к концу, если вы просто хотите получить результат, но давайте пройдемся по этому вопросу вместе. Вот проблемная часть вашего кода:

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);
0

Другие решения

Других решений пока нет …