-2

When running bash scripts in a terminal $1 will represent the value entered after the program.

Example: typed(a bash script)

#!/bin/bash
echo "You typed: " $1

when you enter "./typed something" in a terminal you will get "You typed: something" back.

I would like to know how to do "./a.out test" and have test be the value of std::string userinput

my code:

#include <iostream>
std:string userinput;
int main() {
    std::cout << "You typed: " << userinput << "\n";
    return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user3771450
  • 51
  • 2
  • 6
  • `argc` and `argv[]` are likely what you want. – WhozCraig Jun 26 '14 at 23:46
  • 3
    I don't understand why you lose more time to write a question on StackOverflow when a 2 second Google search can solve your problem. – Unda Jun 26 '14 at 23:47
  • [Read this](http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main), then [read this](http://en.cppreference.com/w/cpp/language/main_function) – WhozCraig Jun 26 '14 at 23:50
  • I tried googling it a bit but did not find any information. – user3771450 Jun 27 '14 at 00:56

3 Answers3

3

Yeah it is argv[1]

#include <iostream>
int main(int argc, char *argv[])
{
    std::cout << "You typed: " << argv[1] << "\n";
    return 0;
}
bentank
  • 616
  • 3
  • 7
3

When you declare your main function, declare it as follows :

int main(int argc, char* argv[]) {
    // your code here
}

These are parameters passed in to your program whenever it is run. Argc is argument count, and is the number of arguments that was passed to your program (including your executable). argv is then an array which contains the arguments provided to your program.

For example :

./myprogram.out file1.txt file2.txt
argv[0] = "./myprogram.out"
argv[1] = "file1.txt"
argv[2] = "file2.txt"
Alex P
  • 530
  • 1
  • 6
  • 13
2
#include <iostream>
int main(int argc, char* argv[])
{
    if (argc > 1) {
        std::cout << "You typed: " << argv[1] << std::endl;
    }
    return 0;
}

If you want more complicated control, try boost::program_options

swang
  • 5,157
  • 5
  • 33
  • 55
  • Someone who uses boost to get program arguments is nothing more than a lumberjack trying to cut butter with chainsaw – Larta Jun 27 '14 at 07:17