Implment something in command line.

Write your question here.

1
2
3
4
5
6
7
  #include <stdio.h>
  int add1(int a){
      return a + 1;
    }
  int main(int argc, char *argv[]){
            ???????????
   }


So anyways I want to implement my code such that when I run and compile the program.
the prompt will pop up and if i type

add1 1
2
add1 3
4
add1 6
7

thanks!
First, check to see if there the number of arguments passed isn't 2 (your program and the variable). If so, print an error message / usage message and quit. Otherwise, transform the relevant argument (argv[1]) into a number and print your add1 function.
Last edited on
^^^

nonono. I know how to get the program to work if all I want to is to get my function working.
int a;
printf("type a number to add one");
scanf("&d",&a);
printf("&d",add1(a));
getch();

What I want my program to do is if I compile it and type the following in the command prompt
"add1 1" it will automatically give me 2
then if i type "add 2" it will automatically give me 3.

Something like that.
Last edited on
Yes, that is what I was saying. Here, I'll even give you an example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <stdlib.h>

int add1(int num) { return num+1; }

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

    // Print the number
    printf("%d\n", add1(atoi(argv[1])));

    return 0;
}
I think the user wants an endless input loop where he can type add1 x multiple times and it will add one and output. Just put a loop around it until you wish to quit.
^ +1
I'm not 100% positive how scanf works but can't you just read in a string and then an integer? error checking on code probably would be helpful too.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <iostream>
#include <string>

int main()
{
    std::string str;
    int i;
    do
    {
        std::cout << "Please enter command: ";
        std::cin >> str >> i;
        if( str == "add1" )
            std::cout << i + 1 << std::endl;
    } while ( str != "quit" );
}
Topic archived. No new replies allowed.