-5

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 <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;
} 

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

Poo Po
  • 11
  • 3
  • it is looking for the Perfect Numbers the arguments is 100 and it need to print 6, 28 – Poo Po Jan 09 '23 at 07:47
  • 2
    Read about [main function](https://en.cppreference.com/w/cpp/language/main_function): the `argc` is the number of arguments passed to the program. – heap underrun Jan 09 '23 at 07:49

1 Answers1

0

Something like this

int main(int argc, char* argv[]) {
    if (argc < 2) {
        cerr << "Not enough arguments\n";
        return -1;
    }
    int limit = atoi(argv[1]); // convert first argument to integer
    ...
john
  • 85,011
  • 4
  • 57
  • 81
  • thanks for ans the question, in the note it is using (const int limit = argc > 1 ? atoi(argv[1]) : 1000;) what is the different – Poo Po Jan 09 '23 at 08:01
  • `atoi` is possibly not the best choice due to lack of error handling – Alan Birtles Jan 09 '23 at 08:03
  • @PooPo Can you not follow the logic? `argc` is the number of arguments given to the program. In my version if there are not enough arguments I print an error message and quit. In your version if there are not enough arguments a default value of 1000 is used. – john Jan 09 '23 at 08:06