ch3-ArgsToInts (Print command-line args as ints in C/C++)
Chapter_3 Exercise_3-21 CommandLineArgs | Exercise_3-22 |
ArgsToInts TCP1, p. 202 (argstoints.c, ArgsToInts.cpp)
argstoints.c download
#include <stdio.h> // for printf()
#include <stdlib.h> // for atoi()
int main(int argc, char* argv[])
{
int i;
for(i = 1; i < argc; i++) // ignore argv[0], program name
{printf("%d\n", atoi(argv[i]));}
return 0;
}
/*
gcc argstoints.c -o argstoints
./argstoints // no args, prints nothing
./argstoints 10 010 0x10 // ignores octal and hex formats
10
10
0
./argstoints a b c // ignores ASCII
0
0
0
./argstoints .012 1.25 23.4E10 1.9 -0.9 // ignores fractional part
0
1
23
1
0
./argstoints 2147483647 -2147483648
2147483647 // INT_MAX // limits.h
-2147483648 // INT_MIN
./argstoints 2147483648 -2147483649 // 1 past limits
-2147483648 // INT_MIN (overflow, modulo 2 arithmetic)
2147483647 // INT_MAX (underflow)
./argstoints 2147483649 -2147483650 // 2 past limits
-2147483647 // INT_MIN + 1
2147483646 // INT_MAX - 1
./argstoints 12345678901234567890 -12345678901234567890
-1 // overflow, too big to handle
0 // underflow (20 digits)
*/
ArgsToInts.cpp download
#include <iostream>
#include <cstdlib> // for atoi()
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 << atoi(argv[i]) << endl;}
return 0;
}
/*
g++ ArgsToInts.cpp -o ArgsToInts
./ArgsToInts // no args, prints nothing
./ArgsToInts 10 010 0x10 // ignores octal and hex formats
10
10
0
./ArgsToInts a b c // ignores ASCII
0
0
0
./ArgsToInts .012 1.25 23.4E10 1.9 -0.9 // ignores fractional part
0
1
23
1
0
./ArgsToInts 2147483647 -2147483648
2147483647 // INT_MAX // climits or limits.h
-2147483648 // INT_MIN
./ArgsToInts 2147483648 -2147483649 // 1 past limits
-2147483648 // INT_MIN (overflow, modulo 2 arithmetic)
2147483647 // INT_MAX (underflow)
./ArgsToInts 2147483649 -2147483650 // 2 past limits
-2147483647 // INT_MIN + 1
2147483646 // INT_MAX - 1
./ArgsToInts 12345678901234567890 -12345678901234567890
-1 // overflow, too big to handle
0 // underflow (20 digits)
*/
Chapter_3 Exercise_3-21 CommandLineArgs | BACK_TO_TOP | Exercise_3-22 |
Comments
Post a Comment