I need to get an argument and convert it to an int. Here is my code so far:
#include <iostream>
using namespace std;
int main(int argc,int argvx[]) {
int i=1;
int answer = 23;
int temp;
// decode arguments
if(argc < 2) {
printf("You must provide at least one argument\n");
exit(0);
}
// Convert it to an int here
}
Since this answer was somehow accepted and thus will appear at the top, although it’s not the best, I’ve improved it based on the other answers and the comments.
The C way; simplest, but will treat any invalid number as 0:
The C way with input checking:
The C++ iostreams way with input checking:
Alternative C++ way since C++11:
All four variants assume that
argc >= 2. All accept leading whitespace; checkisspace(argv[1][0])if you don’t want that. All exceptatoireject trailing whitespace.