I am suppose to read the number of thread requested by the client. So if someone run my program like this:
./test 2 I have to read the number of thread equal to 2. I try getchar() but it's not working. Any idea?
Here is a minimal example with complete, correct error checking and diagnostic messages. Note that setting errno to 0 is necessary for distinguishing range errors from valid strtoul() outputs, this is an annoying quirk of the function.
#include <stdlib.h> #include <stdio.h> #include <errno.h> int main(int argc, char *argv[]) { if (argc != 2) { fputs("usage: test NTHREAD\n", stderr); exit(1); } char *e; errno = 0; unsigned long nthread = strtoul(argv[1], &e, 0); if (!*argv[1] || *e) { fputs("error: invalid NTHREAD\n", stderr); exit(1); } if (nthread == (unsigned long) -1 && errno == ERANGE) { fputs("error: NTHREAD out of range\n", stderr); exit(1); } // Your code goes here } errno = 0 in order to allow the block of code to be copied and pasted into sections where the precondition errno == 0 is not guaranteed. It also means that people reading the code do not have to examine surrounding code to verify the precondition.*e and nthread would cause errors)...int main(int argc, int **argv)
Using arguments of main, you should know the first argument argv[0] is the name of current executing file, and the following arguments are the parameters sent to your program.
In your case, you must read argv[1].
Always check argc to count the entered arguments.
argv[0]always contains the program name invoked by the command. Thus, the first real argument is stored inargv[1]. But you have to check if such an argument exist. To do so, just readargc, it tells you the number of elements pointed byargv. In your case, it should equal 2.