C++ int main(int argc, char* argv[])

huangapple go评论72阅读模式
英文:

C++ int main(int argc, char* argv[])

问题

如何将int argc和char* argv保存到int something中。

我试图从一个测试程序中获取参数并保存到int ****中;

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char* argv[]) {
    int limit = argc;
    cout << limit << endl;
    for (int candidate = 2; candidate < limit; candidate++) {
        int total = 1;
        for (int factor = 2; factor * factor < candidate; factor++) {
            if (candidate % factor == 0)
                total += factor + candidate / factor;
        }
        if (total == candidate) {
            cout << candidate << ' ';
        }
    }
    return 0;
}

程序预设参数为100,但无法保存到int limit

英文:

how do i save int argc, char* argv in to int someting.

i am trying to get the arguments from a test program and save it into int ****;

#include &lt;iostream&gt; 
#include &lt;cstdlib&gt;
using namespace std;

int main(int argc, char* argv[]) {
 int limit = argc;
 cout&lt;&lt; limit &lt;&lt;endl;
 for (int candidate = 2; candidate &lt; limit; candidate++) {
    int total = 1;
    for (int factor = 2; factor * factor &lt; candidate; factor++) {
        if (candidate % factor == 0)
            total += factor + candidate / factor;

    }
    if (total == candidate) {
        cout &lt;&lt; candidate &lt;&lt; &#39; &#39;;
    }
}
return 0;
} 

and the program is pre-set the arguments is 100, and it just can't save in to int limit

答案1

得分: 0

以下是翻译好的部分:

int main(int argc, char* argv[]) {
    if (argc < 2) {
        cerr << "参数不足\n";
        return -1;
    }
    int limit = atoi(argv[1]); // 将第一个参数转换为整数
    ...
英文:

Something like this

int main(int argc, char* argv[]) {
    if (argc &lt; 2) {
        cerr &lt;&lt; &quot;Not enough arguments\n&quot;;
        return -1;
    }
    int limit = atoi(argv[1]); // convert first argument to integer
    ...

huangapple
  • 本文由 发表于 2023年1月9日 15:42:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定