-1

I am a begineer in C++ ! While playing with just learned skils i m trying to create a program that calculates your age by your Birth year passed in command line. I dont know why the program didn't even compile !

MY CODE :

#include <iostream>
using namespace std;

int main(int argc, char* argv[]){
  if (argc < 2){
    cout<<"Your Age is 2022-<YOB> \n";
    return 3;
  }
  int age;
  age = 2022-argc[1]
  cout<<"Your Age is "<<age<<endl;
  return 0;
}

ERROR:

./main.cpp:10:18: error: subscripted value is not an array, pointer, or vector
  age = 2022-argc[1]
             ~~~~^~
1 error generated.
make: *** [Makefile:9: main] Error 1
exit status 2
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Tuchar Das
  • 43
  • 6
  • 1
    `argc` is an `int` so you can't use `operator[]` with it. – Jason Sep 13 '22 at 06:10
  • Please don't tag other unrelated programming languages, only the one you're actually using. – Some programmer dude Sep 13 '22 at 06:10
  • 2
    As for your problem, you probably want to use `argv[1]` instead. *But* that won't work anyway, since `argv[1]` is a *string* (more accurately a pointer to the first character of a null-terminates string). If you want to use it as an integer you must first [convert](https://en.cppreference.com/w/c/string/byte/strtoul) it to one. – Some programmer dude Sep 13 '22 at 06:12
  • @Someprogrammerdude Yeah i know that. But my code isn't OOP based it might produce same result in either of them. – Tuchar Das Sep 13 '22 at 06:28

1 Answers1

1

The problem is that argc is an int, so we can't use operator[] with it.

To solve this you can use argv and std::istringstream as shown below:

int main(int argc, char *argv[])
{
    if(argc < 2){
        std::cout <<"Your age is 2022-<YOB>\n";
        return 0;         
    } 
    std::istringstream ss(argv[1]);
    int age = 0;
    //convert string arg to int age
    ss >> age;

    std::cout<<"Your age is: "<<age<<std::endl;
}
Jason
  • 36,170
  • 5
  • 26
  • 60
  • Can u Explain a bit more about isstringstream and its syntax ? – Tuchar Das Sep 13 '22 at 06:26
  • @TucharDas Sure, the same is explained [here](https://stackoverflow.com/a/62776735/12002570). Basically, we're converting a string to an int. – Jason Sep 13 '22 at 06:28