Exercise 3-22 (Print command-line args as long and double)
Chapter_3 Exercise_3-21 ArgsToInts | FloatBinary Exercise_3-23 |
Exercise 3-22 TCP1, p. 229
Exercise 3-22. Create two new programs starting from ArgsToInts.cpp (see ch3-ArgsToInts) so they use atol() and atof(), respectively.
CONTENTS: ArgsToLongs.cpp ArgsToDoubles.cpp
ArgsToLongs.cpp download
#include <iostream>
#include <cstdlib> // for atol()
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
for(int i = 1; i < argc; i++) // ignore argv[0], program name
{cout << atol(argv[i]) << endl;}
return 0;
}
/*
g++ ArgsToLongs.cpp -o ArgsToLongs
./ArgsToLongs // no args, prints nothing
./ArgsToLongs 10 010 0x10 // ignores octal and hex formats
10
10
0
./ArgsToLongs a b c // ignores ASCII
0
0
0
./ArgsToLongs .012 1.25 23.4E10 1.9 -0.9 // ignores fractional part
0
1
23
1
0
./ArgsToLongs 1234567890 9223372036854775807 -9223372036854775808
1234567890
9223372036854775807 // LONG_MAX // see climits or limits.h
-9223372036854775808 // LONG_MIN
./ArgsToLongs 9223372036854775808 -9223372036854775809 // 1 past limits
9223372036854775807 // LONG_MAX
-9223372036854775808 // LONG_MIN
*/
ArgsToDoubles.cpp download
#include <iostream>
#include <cstdlib> // for atof()
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
for(int i = 1; i < argc; i++) // ignore argv[0], program name
{cout << atof(argv[i]) << endl;}
return 0;
}
/*
g++ ArgsToDoubles.cpp -o ArgsToDoubles
./ArgsToDoubles // no args, prints nothing
./ArgsToDoubles 10 010 0x10 // ignores octal, but not hex
10
10
16
./ArgsToDoubles a b c // ignores ASCII
0
0
0
./ArgsToDoubles 0xa 0xb 0xc // hex values
10
11
12
./ArgsToDoubles .012 1.25 23.4E10 1.9 -0.9
0.012
1.25
2.34e+11
1.9
-0.9
./ArgsToDoubles 12345678901234567890 -12345678901234567890
1.23457e+19
-1.23457e+19
*/
Chapter_3 Exercise_3-21 ArgsToInts | BACK_TO_TOP | FloatBinary Exercise_3-23 |
Comments
Post a Comment