0

I'm learning C++ for school and I'm confused on how to integrate command line arguments into my code

    int n = 1;
    int c = 0;
    n = argv[1];
    c = int(argv[2]);
    findPrimes(n, c); 
    return 0;
}

That's my main function so far, but n = argv[1]; is a type error, and c = int(argv[2]); is a loss of data error. I know I'm rather far off, so any help to both improve my question and solve my problem is appreciated.

Zatone
  • 3
  • 2
  • 1
    argv is an array of c-strings. You need to convert the string into the correct thing. – NathanOliver Sep 26 '22 at 21:26
  • 1
    Ok, my C++ array knowledge is bad at best, how would I go about doing that? @NathanOliver – Zatone Sep 26 '22 at 21:27
  • 1
    https://stackoverflow.com/questions/6093414/convert-char-array-to-single-int – NathanOliver Sep 26 '22 at 21:30
  • OT: You should always verify that the correct number of arguments was passed. Your program would exhibit UB if the user failed to type the required arguments. – drescherjm Sep 26 '22 at 21:54
  • I start my C++ code this way: `int main(int argc, char** argv) { vector args(argv+1, argv+argc); /*...*/` which I find easier to work with a vector of strings rather than C style argc and argv. – Eljay Sep 26 '22 at 22:00

1 Answers1

0

To convert a char* string into an int, you can use the C library atoi(), sscanf() or other equivalent function:

#include <cstdlib>

int n = std::atoi(argv[1]);
#include <cstdio>

int n;
std::sprintf(argv[1], "%d", &n);

Or, you can use the C++ std:stoi() function:

#include <string>

int n = std::stoi(argv[1]);

Or, the C++ std::istringstream stream class:

#include <sstream>

int n;
std::istringstream(argv[1]) >> n;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770