问题
I need to add fractions given by the user through command prompt in the format
a/b b/c
I thought I could do it this way:
n1 = atoi(argv[1]);
d1 = atoi(argv[3]);
n2 = atoi(argv[4]);
d2 = atoi(argv[6]);
Thereby skipping the slashes, but this just crashes the program. Is there some way to skip over certain characters passed as arguments through command prompt? Thank you in advance.
回答1:
If the user writes:
add_fractions 1/2 2/3
then your program is given just 3 arguments:
argv[0] = "add_fractions"
argv[1] = "1/2"
argv[2] = "2/3"
argv[3] = 0
and argc
is 3.
You would have to do something like this (after checking that you were given 2 arguments):
char *ptr;
n1 = atoi(argv[1]);
if ((ptr = strchr(argv[1], '/') != 0)
d1 = atoi(ptr+1);
else
d1 = 1;
n2 = atoi(argv[2]);
if ((ptr = strchr(argv[2], '/') != 0)
d2 = atoi(ptr+1);
else
d2 = 1;
Or you could pack the repeated sequence of statements into a function (with a slightly different twist in the logic):
void read_fraction(char const *str, int *num, int *den)
{
char *ptr;
*num = atoi(str);
if ((ptr = strchr(str, '/') == 0)
ptr = "/1";
*den = atoi(ptr+1);
}
and in main()
:
read_fraction(argv[1], &n1, &d1);
read_fraction(argv[2], &n2, &d2);
You might want to think about validation; the numerator becomes 0 if there isn't a number as the first part of the string, but the denominator becomes 0 if there is a slash and there isn't a number after the slash, which might not be exactly what you want. One fix is to set the denominator to 1 if the value from atoi(ptr+1)
is 0. It's a cop-out, but prevents rampant crashes. Or you could use another completely different implementation in the body of the function:
int read_fraction(char const *str, int *num, int *den)
{
if (sscanf(str, "%d/%d", num, den) != 2)
return -1;
return 0;
}
And then check in main()
:
if (read_fraction(argv[1], &n1, &d1) == 0 &&
read_fraction(argv[2], &n2, &d2) == 0)
...process valid fractions...
else
...make appropriate comments about how to use the program...
Using a function is 'better' from several points of view. In The Pragmatic Programmer, it is called the DRY principle: Don't Repeat Yourself.
Kernighan and Plauger summarized it neatly in their book The Elements of Programming Style:
- The subroutine call permits us to summarize the irregularities in the argument list, where we can see quickly what is going on.
- The subroutine itself summarizes the regularities of the code, so repeated patterns need not be used.
回答2:
a/b b/c
It just creates 2 entries in the argument list, one is a/b
and another is b/c
.
So, argv[0]
, argv[1]
and argv[2]
are valid and argc
is 3
.
Spaces are important to separate arguments (unless you wrap a entry inside ""
)
来源:https://stackoverflow.com/questions/19923006/how-to-exclude-arguments-passed-from-command-prompt-argc-argv-in-c