对有理数的操作,我要从stdin和命令行获得输入。当我尝试将argv值cpy到变量时,我得到错误:从'char'无效转换为'char *'[-fpermissive] strcpy(choice,argv [1]);
#include <stdio.h>
#include<string.h>
typedef struct rational
{ int num,den;} Rational;
Rational rationalNumMain(int argc, const char** argv)
{
Rational r1,r2,r;char choice;
if(argc==1)
{
scanf("%c",&choice);
scanf("%d",&r1.num);
scanf("%d",&r1.den);
scanf("%d",&r2.num);
scanf("%d",&r2.den);
}
else
{ strcpy(choice,argv[1]);
strcpy(r1.num,argv[2]);
strcpy(r1.den,argv[3]);
strcpy(r2.num,argv[4]);
strcpy(r2.den,argv[5]);
}
switch(choice)
{
case 'A':
r.num=(r1.num*r2.den)+(r1.den*r2.num);
r.den=(r1.den*r2.den);
return r;
break;
case 'S':
r.num=(r1.num*r2.den)-(r1.den*r2.num);
r.den=(r1.den*r2.den);
return r;
break;
case'M':
r.num=(r1.num*r2.num);
r.den=(r1.den*r2.den);
return r;
break;
case 'D':
r.num=(r1.num*r2.den);
r.den=(r1.den*r2.num);
return r;
break;
} }
int main(int argc, const char** argv)
{
Rational r1,r2,result;
result=rationalNumMain(argc, argv);
printf("%d,%d", result.num, result.den);//prints the output
return 0;
}
答案 0 :(得分:4)
使用sscanf
解析来自argv
的输入。
sscanf(argv[1], "%c", &choice);
sscanf(argv[2], "%d",&r1.num);
sscanf(argv[3], "%d",&r1.den);
sscanf(argv[4], "%d",&r2.num);
sscanf(argv[5], "%d",&r2.den);
答案 1 :(得分:0)
'choice'被声明为char而不是char *所以这将失败
strcpy(choice,argv[1]);
因为strcpy将两个字符串指针作为参数。
为了从argv取消引用它的第一个字符
choice = *argv[1];