Command line

I'm struggling to get to grip's with:

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

In an exercise i've got to take 2 argument's and concatenate them, Outputting
them in a string. But there is next to no explaination as to how passing and reading the argument's from a command line is accomplished.
Can someone explain where i'm going wrong?

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
    std::string third;
    char first = *argv[1];
    char second = *argv[2];
    third[0] = first;
    third[1] = second;
    std::cout << third;
}
You should check whether ar least two command line parameters were specified. The code could look the following way

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
    std::string third;

    if ( argc > 1 ) third = argv[1];
    if ( argc > 2 ) third += argv[2];

    std::cout << third;
}
Last edited on
Thank's vlad.
Topic archived. No new replies allowed.