Melkon
Melkon

Reputation: 37

Input from the execution line in the terminal in c

The problem that i have is that i have to write a hanois tower game in c and the input for the number of the rings must not be in the programm but the code must read the number of rings in the execution.

Example: ./hanoistower 3

And the code should get the 3 as the input. How can i do that?

Upvotes: 0

Views: 17382

Answers (3)

I strongly suggest reading a good C programming book (in 2020, Modern C).

It will be much faster than asking questions here. Don't forget to also read the documentation of your C compiler (perhaps GCC), your build automation tool (e.g. GNU make or ninja), and debugger (perhaps GDB). If you code on and for Linux, read also Advanced Linux Programming and syscalls(2), and the documentation of GNU glibc (or of musl-libc, if you use it).

Hovever, the program arguments is given as a null terminated array of strings to the main function, which is usually declared as

 int main (int argc, char**argv) { /*...*/ }

if you run your program with ./hanoistower 3 and if your hanoistower.c is your source code (which you need to compile with debugging and warning enabled, i.e. gcc -Wall -g hanoistower.c -o hanoistower on Linux) then you have one extra argument, so

  1. argc == 2
  2. argv[0] is the "./hanoistower" string
  3. argv[1] is the "2" string (use atoi to convert it to an int)
  4. argv[2] is NULL

Please, please learn to use the debugger (gdb on Linux).

Upvotes: 2

allwyn.menezes
allwyn.menezes

Reputation: 804

Just add, argc and argv to the list of main method parameters, as shown below:

int main ( int argc, char *argv[] )

Then use argv as the variable to specify number of rings inside your code.

Upvotes: 0

nos
nos

Reputation: 229284

Command line arguments are propagated as strings through the main() function of your C program.

In int main(int argc, char *argv[]) argc is the number of arguments, and argv is an array of strings containing the arguments. Note that the program name itself is always the first "argument".

As the arguments are passed as strings, you likely need to convert your 3 to an integer, which can be done with the atoi function. Here's a start:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   int rings;
   if(argc != 2) {
       printf("Usage: %s number-of-rings\n",argv[0]);
       return 1;
   }

   rings = atoi(argv[1]);
   printf("Using number-of-rings = %d\n", rings);
...

   return 0;
}

Upvotes: 4

Related Questions