-1

How do you get input using prompt? I tried compiling the code bellow into "a.exe" and executing it from CMD like "gcc a.exe 5", but it doesn't output the number like it was supposed to.

#include <stdio.h>

int main(int a)
{
    printf("%d\n", a);
    return 1;
}

Have I done anything wrong when installing the compiler or am I trying to run it wrong?

Kyokon
  • 21
  • 1
  • 2
  • 1
    These are called "command-line arguments". You can read more at [this tutorial](http://crasseux.com/books/ctutorial/argc-and-argv.html). – user12205 Apr 12 '15 at 01:21
  • `gcc test.c` then `a.exe 5`, print `2` is number of token of comand line – BLUEPIXY Apr 12 '15 at 01:34
  • also `int main(int a)` is invalid syntax. E.g. `int main(int n, char *v[]){ if(n > 1) printf("%s\n", v[1]); return 0;}` – BLUEPIXY Apr 12 '15 at 01:37
  • possible duplicate of [C - reading command line parameters](http://stackoverflow.com/questions/5157337/c-reading-command-line-parameters) – masoud Apr 12 '15 at 12:20

3 Answers3

3

To get input using the prompt, the easiest way would simply be to use a scanf statement. scanf basically waits for, and scans user input, which can then be stored as a variable. For example, a code that would take input for "Give me a number." and then spits back the result would be:

#include <stdio.h>

int main()
{
    int num; //Initializes variable
    printf("Please give me a number.\n"); //Asks for input
    scanf("%d", &num); //scanf is the function, %d reserves the space, and the &*variable* sets the input equal to the variable.  
    getchar(); //Waits for user to input. 
    printf("Your number was %d.\n", num); //Spits it back out.
    return 0;
}

The output would be:

[PROGRAM BEGINS]
Please give me a number.
>>>5
Your number was 5. 
[PROGRAM ENDS]
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
3

Your main() parameters are wrong, you should do it this way:

int main(int argc, char **argv) {
     if(argc > 2) {
         printf("%s\n", argv[2]);
     }
     else {
         printf("No arguments\n");
     }          
}

Note that int argc represents the number of parameters and char **argv is an array containing all the parameters, as strings, including "gcc", "a.exe", etc. In your case, if you run your program this way: gcc a.exe 5, your parameters would be: argc = 3, argv = ["gcc", "a.exe", "5"]

Lior Erez
  • 1,852
  • 2
  • 19
  • 24
  • This would just print the supplied argument, regardless if it is a digit or not. – Deanie Apr 12 '15 at 01:46
  • @Deanie If you want to convert it to an integer you can use `atoi()`. However, you should always check if your string can actually be converted to and integer before using `atoi()`. – Lior Erez Apr 12 '15 at 01:56
2
#include <stdio.h>

int main(int argc, char *argv[])
{
    if(argc == 2)
        printf("%d\n", atoi(argv[1]));

    return 0;
}
Deanie
  • 2,316
  • 2
  • 19
  • 35