I get error [Error] no match for 'operator-' (operand types are 'std :: string {aka std :: basic_stringchar}' and 'int') calculate the age

3
#include <iostream>
#include <ctype.h>
#include<stdio.h>
using namespace std;
int main(void){

    string nombre, segundonombre, primerapellido, segundoapellido, fecha;

 cout<<"Este Programa Te Dira Tu Nombre Completo"<<endl;
 cout<<"Porfavor ingresa Tu Primer Nombre: "<<endl ;
 cin>>nombre ; 
 cout<<"Porfavor ingresa Tu Segundo Nombre: "<<endl;
 cin>>segundonombre; 
 cout<< "Ahora Tus Apellidos: \n\n"<<endl;
 cout<<"Porfavor ingresa Tu Primer Apellido: "<<endl;
 cin>>primerapellido; 
 cout<<"Porfavor ingresa Tu Segundo Apellido: "<<endl;
 cin>>segundoapellido; 
  cout<<"Ingresa Su fecha de nacimiento: "<<endl;
 cin>>fecha; 
 cout<<"tu edad es: "<<endl;
 cin>>fecha-2017; 
 cout <<"Tu Te Llamas: "<<nombre<<"\n\n"<<segundonombre<<"\n\n"<<primerapellido<<"\n\n"<<segundoapellido<<"\n\n"<<fecha<<"\n\n"<<endl;


    return 0;
}
    
asked by Alberto Dolores Díaz 25.04.2017 в 06:09
source

2 answers

3

your error is in this line:

cin>>fecha-2017;

fecha is of type string to which you are trying to subtract an "int"

can treat the following for error:

//..
cin>>fecha; //asignas el valor a fecha
fecha = std::to_string(std::stoi(fecha)-2017);
//..

std::stoi(fecha) add the parameter to an integer.

std::to_string(...) add the parameter to a string

Now that string is assigned to fecha with fecha =...

    
answered by 25.04.2017 в 06:39
2
string fecha;

cout<<"Ingresa Su fecha de nacimiento: "<<endl;
cin>>fecha;
cout<<"tu edad es: "<<endl;
cin>>fecha-2017;

In the last line you have two errors:

  • date is of string , which does not support arithmetic operations
  • you are using cin instead of cout

To solve the first problem you must convert the date into a numerical representation, in such a way that it is possible to perform arithmetic operations with it. To be able to do this before you have to be clear that you must specify what will be the expected format of the date:

  • dd / mm / YYYY
  • mm / dd / YYYY
  • YYYY / mm / dd
  • ??

Once you have specified the format you can start processing the date. Let's assume that you have chosen the first option. A simple way to access it would be:

int ExtraerAnio(std:: string const& fecha)
{
  int dia,mes,anio;

  std::sscanf(fecha.c_str(), "%d/%d/%d", &dia, &mes, &anio) != 3)
  {
    // Error de parseo
  }

  return anio;
}

With what your code would be

cout<<"tu edad es: "<<endl;
cout>>ExtraerAnio(fecha)-2017;

The code could be improved to take into account if you are not yet years old or not taking into account the day and month

    
answered by 25.04.2017 в 07:27