This month’s Exercise is rather simple, though it doesn’t promise a simple solution. Instead, I offer three solutions. One of which is obvious and two are kind of out there. They all work, which is the point.
My first solution is the first one I thought of, the “easy” solution. It uses scanf() to read in two values, one after the other, separated by whitespace.
2024_06-Exercise-a.c
#include <stdio.h> int main() { int a,b; printf("Enter two values: "); scanf("%d %d",&a,&b); printf("%d + %d = %d\n",a,b,a+b); return 0; }
Remember that scanf() is a stream function. It tries to match its input string with standard input, so it looks for two values separated by a space. Here’s a sample run:
Enter two values: 5 6
5 + 6 = 11
For my second example, I decided to read the command line for values:
2024_06-Exercise-b.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a,b; if( argc<3 ) { puts("Enter two values"); exit(1); } a = strtol(argv[1],NULL,10); b = strtol(argv[2],NULL,10); printf("%d + %d = %d\n",a,b,a+b); return 0; }
The if test confirms that three arguments are present on the command line: the program name followed by two items that the code reads as values. When the arguments aren’t present, a message is output, which serves as the program’s prompt. (The program name could also be something like InputTwoValues
.)
The strtol() function converts text from a string into a long int value in the given base. The first argument is the string, where I use command line arguments argv[1]
and then argv[2]
. The second argument is NULL, which directs strtol() to stop looking for additional values. The final argument is the number base, 10
for decimal. Here are my sample runs:
$ ./a.out
Enter two values
$ ./a.out 100 60
100 + 60 = 160
My final example exploits the second argument in the strtol() function. When this value is non-NULL, it’s used as an address to hold a reference to the invalid character after the first found value. This pointer is used to continue scanning the same string for additional values:
2024_06-Exercise-c.c
#include <stdio.h> #include <stdlib.h> int main() { const int size=16; char input[size]; char *next; int a,b; printf("Enter two values: "); fgets(input,size,stdin); a = strtol(input,&next,10); b = strtol(next,NULL,10); printf("%d + %d = %d\n",a,b,a+b); return 0; }
The second argument to strtol() is a pointer-pointer. Declaring it as char **next
doesn’t work, mostly because the variable must be used directly in the second strtol() call.
In the code, next
is declared as a pointer, but it’s used in the strtol() call with the &
(address-of) operator to be a pointer-pointer. This code generates on warnings or errors in clang. Here is a sample run:
Enter two values: 100 -20
100 + -20 = 80
I’m certain other solutions are available as well. These demonstrate the many possible ways to code such a problem, specifically to obtain user input for the calculation. I hope your solution(s) met with success.