简体   繁体   中英

C++ Command Line Arguments

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.

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 <cstdlib>

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 std::istringstream stream class:

#include <sstream>

int n;
std::istringstream(argv[1]) >> n;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM