简体   繁体   English

C++ 命令行 Arguments

[英]C++ Command Line Arguments

I'm learning C++ for school and I'm confused on how to integrate command line arguments into my code我正在为学校学习 C++,我对如何将命令行 arguments 集成到我的代码中感到困惑

    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];到目前为止,这是我的主要 function,但 n = argv[1]; is a type error, and c = int(argv[2]);是类型错误,并且 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:要将char*字符串转换为int ,您可以使用 C 库atoi()sscanf()或其他等效的 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:或者,您可以使用 C++ std:stoi() function:

#include <string>

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

Or, the std::istringstream stream class:或者, std::istringstream stream class:

#include <sstream>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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