gpt4 book ai didi

c - 仅解析给定参数中的数字

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:36 26 4
gpt4 key购买 nike

如何在 C 语言中从任意给定数量的参数中仅解析出前 10 个数字,然后将其输出为电话号码?例如,如果一个文件名为 function,而给定的命令是 function hi1234567890,它将返回 (123)456-7890。类似地,如果用户输入三个参数 function 123 hi 456,它可能会返回一些内容,表示没有足够的数字。这是我到目前为止所拥有的:

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

int main (int argc, char *argv[]) {
char phone[13]; // array to store phone number

int i;
int j;
int len;
int num;

for(i = 1; i < argc; i++) {
len = strlen(argv[i]);
for(j = 0; j < len; j++) {
num = atoi(argv[i][j]);
if ( isdigit(num) != 0 ) {
phone[j] = argv[i][j];
}
}
}
}

这肯定是行不通的,atoi() 有问题,这反过来导致 isdigit() 无法工作,我没有将它正确地存储在数组中。

最佳答案

正如 chux 所指出的,您必须逐个字符地解析字符串。 atoi() 和 strtol() 将读取所有数字(并丢弃前导零)直到遇到非数字,这使您难以控制读取的字符数。

沿线尝试一些东西

int main (int argc, char *argv [])
{
char phone_number [14];
int digit_count; /* counter for digits */
int p; /* pointer into phone_number */
int i, a; /* loop variables */
int arg_len; /* no. of chars in current arg */

/* loop over arguments */
for (a=1; a<argc; a++)
{
arg_len = strlen (argv [a]);
phone_number [0] = '(';
p=1;
digit_count=0;

/* parse current argument */
for (i=0; i<arg_len; i++)
{
/* safe digit */
if (isdigit (argv [a][i]))
{
phone_number [p] = argv[a][i];
p++;
digit_count++;
}

/* insert format */
if (p == 4)
{
phone_number [p] = ')';
p++;
}
if (p == 8)
{
phone_number [p] = '-';
p++;
}

/* read ten digits -> finished */
if (digit_count == 10)
{
phone_number [p] = '\0';
break;
}
}

/* check for enough digits */
if (digit_count < 10)
{
printf ("Argument had only %d digits\n!", digit_count);
continue;
}

printf ("Phone_number (%d): %s\n", a, phone_number);
}
}

这给出:

$ ./a.out hi1234567890 abc123456jfhj789649 a75849gfj5
Phone_number (1): (123)456-7890
Phone_number (2): (123)456-7896
Argument 3 had only 6 digits

关于c - 仅解析给定参数中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51408893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com