Monday 15 September 2014

function - C - argc changes with operation -



function - C - argc changes with operation -

for reason argc argument changes 4 6 if instead of "a+bi + c+di" write "a+bi * c+di" , don't know why. happening , how can solve it?

thank you

#include <stdio.h> #include <string.h> #define formatlog "invalid input. required format: <a+bi> <operator> <c+di>" #define inputlog "error: trying operate different sets of numbers" enum { true, false }; typedef struct { double realp, imagp; } complex; int checkifcomplex(char *exp) { unsigned int = 1; if(exp[strlen(exp) - 1] == 'i') while(exp[i] != '\0') { if(exp[i] == '+' || exp[i] == '-') homecoming true; i++; } homecoming false; } complex parsecomplex(char *exp) { complex number; sscanf(exp, "%lf + %lfi", &number.realp, &number.imagp); homecoming number; } int main(int argc, char **argv) { printf("%d", argc); if(argc != 4) { puts(formatlog); homecoming false; } if(argv[2][0] != '%') if(checkifcomplex(argv[1]) || checkifcomplex(argv[3])) { puts(inputlog); homecoming false; } complex result, fterm = parsecomplex(argv[1]), sterm = parsecomplex(argv[3]); switch(argv[2][0]) { case '+': result.realp = fterm.realp + sterm.realp; result.imagp = fterm.imagp + sterm.imagp; break; case '-': result.realp = fterm.realp - sterm.realp; result.imagp = fterm.imagp - sterm.imagp; break; case '*': case 'x': result.realp = fterm.realp * sterm.realp; result.imagp = fterm.realp * sterm.imagp + fterm.imagp * sterm.realp - fterm.imagp * sterm.imagp; default: puts(formatlog); homecoming false; } fprintf(stdout, ">> %g + %gi\n", result.realp, result.imagp); homecoming true; }

it appear '*' beingness treated wild-card , expanded shell before beingness passed application. example,

int main(int argc, char** argv) { int ndx; printf("%d\n", argc); for(ndx = 0; ndx < argc; ndx++) { printf("argument %d %s\n", ndx, argv[ndx]); } homecoming 0; }

produces next output (on ubuntu host, using gcc-4.8 compiler):

******@ubuntu:~/junk$ ./complex a+bi * c+di 6 argument 0 ./complex argument 1 a+bi argument 2 complex argument 3 complex.c argument 4 complex.c~ argument 5 c+di

i can see 2 solutions problem:

(1) escape * this:

xxxxxx@ubuntu:~/junk$ ./complex a+bi \* c+di 4 argument 0 ./complex argument 1 a+bi argument 2 * argument 3 c+di

problem here going have escape symbol has special significance, , doesn't seem natural write *. additionally, i'm not sure how portable going due shells using different escape charaters.

(2) quote entire look this:

xxxxxx@ubuntu:~/junk$ ./complex "a+bi * c+di" 2 argument 0 ./complex argument 1 a+bi * c+di

at to the lowest degree here user can write look in normal form, have remember quote it. additionally, provides protection against user adding additional space in expression, vis a + bi * c+di. problem here utilize needs remember quote look , need bit more parsing extract 2 terms.

c function char arguments main

No comments:

Post a Comment