Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error on Operation of numbers and user input values in cpp

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

./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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading