tags:

views:

163

answers:

7

i have following code

#include <iostream>
using namespace std;
int main(int argc,char arg[]){

    int a=arg[1];
    int b=arg[2];
    int c=a+b;
    cout<<c<<endl;


     return 0;
}

i am using windows 7 microsoft visual c++ 2010 how run it from command line?

+1  A: 

Once you compile this you get an executable. Navigate to the directory containing the executable and run it.

Darin Dimitrov
Unless you know what you are doing that's not exactly helpful. You are making way to many assumptions on implied knowledge.
Martin York
+2  A: 

Open a command prompt from the Start Menu. Use the CD command to change directories to where your exe is. type the name of your exe followed by the arguments.

foo.exe 1 2

or just

foo 1 2

Expect the output (once you've fixed your numerous code errors):

3
Kate Gregory
I certainly wouldn't expect that output.
Noah Roberts
Fair enough, once it is working. But the question I answered was about the actual process of executing and passing arguments.
Kate Gregory
A: 

The compiled output of your program will be in the Debug or Release folder inside the solution folder (at least with default project settings). Just change to that directory and run the .exe file.

Cogwheel - Matthew Orlando
+1  A: 

Go to google and look for a windows console tutorial. You need to start it from the console. Alternatively you can assign command line in the project properties. I'd recommend learning to do both.

BTW, this code almost certainly does not do what you think it does.

Noah Roberts
A: 

Open the Visual Studio Command Prompt (you can find it in the Start Menu)

cd to your source file directory

type:

cl.exe <your file name>.cpp

It will create a file .exe

Matt
Matthew, that's how to compile and link it, not how to run it.
Kate Gregory
Sorry, I misread the question :(
Matt
A: 

Once your code is setup properly it would be something like this.

MyApp 2 3

Or similar

Mitchel Sellers
A: 

Navigate to the directory where the executable (.exe) is located. Then type the executable's name followed by two integer parameters.

C:\TestProg\> TestProg 5 6

The problems in your original example are corrected here:

#include <iostream>
#include <sstream>

int main(int argc, char *arg[])
{
    std::stringstream sa;
    std::stringstream sb;
    int a;
    int b;
    int c;

    if (argc >= 3)
    {    
        // Convert string parameter into an integer.
        sa.str(arg[1]);
        sa >> a;

        if (!sa)
        {
            return 1;    // error
        }

        // Convert string parameter into an integer.
        sb.str(arg[2]);
        sb >> b;

        if (!sb)
        {
            return 1;    // error
        }
    }
    else
    {
        return 1;    // error
    }

    c = a + b;
    std::cout << c << std::endl;
    return 0;
}
Amardeep