[英]C++ Command Line Arguments
我正在為學校學習 C++,我對如何將命令行 arguments 集成到我的代碼中感到困惑
int n = 1;
int c = 0;
n = argv[1];
c = int(argv[2]);
findPrimes(n, c);
return 0;
}
到目前為止,這是我的主要 function,但 n = argv[1]; 是類型錯誤,並且 c = int(argv[2]); 是數據丟失錯誤。 我知道我離我還很遠,所以對改善我的問題和解決我的問題的任何幫助表示贊賞。
要將char*
字符串轉換為int
,您可以使用 C 庫atoi()
、 sscanf()
或其他等效的 function:
#include <cstdlib>
int n = std::atoi(argv[1]);
#include <cstdlib>
int n;
std::sprintf(argv[1], "%d", &n);
或者,您可以使用 C++ std:stoi()
function:
#include <string>
int n = std::stoi(argv[1]);
或者, std::istringstream
stream class:
#include <sstream>
int n;
std::istringstream(argv[1]) >> n;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.