c - 使用函数 getopt 得到除数的个数

标签 c string command-line-arguments getopt

我正在编写一个程序,它接收一个数字并给出除数的数量。 例如 在命令中:

practica -n 30

预期输出:

1,2,3,5,6,10,15,30

我有这个代码:

void divisor(char *temp1);
int main(int argc,char **argv){
int option;
char *n;
 while((option =getopt(argc,argv,"n")) !=-1){
  switch(option){
  case 'n':
  n=optarg;
  break;
 }
}

divisor(n);
}

void divisor(char *temp1){
char f=*temp1;
int n=f-'0';
int a;
a=1;
while (a<n)
{
 if(n%a==0)
 printf("%d,",a);
 a++;
}
a=n;
if(n%a==0)
printf("%d",a);
printf("\b ");
}

我正在使用命令行,程序关闭。

enter image description here

enter image description here

最佳答案

我认为,您的 getopt() 调用应该类似于

while((option =getopt(argc,argv,"n:")) !=-1){  //notice the :

因为您将为该选项提供一个参数(值)。

也就是说,在您的代码中,在 divisor() 函数内,

char f=*temp1;
int n=f-'0';

看起来不对。 temp 是一个 char 指针,取消引用该指针只会给出存储的第一个 char 的值,以及预期值,30 不存储为单个 char,而是存储为字典格式。

我想,你可以使用strtol()将字典表示形式转换为 int 值,例如

int x = strtol(temp, NULL, 0);

关于c - 使用函数 getopt 得到除数的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31154441/

相关文章:

c++默认数组大小覆盖命令行参数

c-如何在多个管道中同时读写?

连接值时发生 Javascript 错误

json - 如何正确解码命令行输入?

c++ - 程序在索引超出范围时终止

string - 用 K 对创建二进制字符串

java - 在 Windows 上的 args[] 数组中传递转义序列

c++ - 考虑到可能的别名,如何编写函数

c - 格式化字符串攻击 - 覆盖 __DTOR_END__

c - 系统调用 "open()"中的 O_TRUNC 实际上并未删除文件内容