Home > Net >  Error on Operation of numbers and user input values in cpp
Error on Operation of numbers and user input values in cpp

Time:09-13

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

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related