Switch from string to int c++

Asked

Viewed 58 times

-2

Next, I’m doing a function that receives the date this way "XX/XX/XXXX" but I have to perform checks as day, month, leap year, these things, and I’m using its format in string on account of the bars. So I thought about transforming the string into int, but I only got with the first two values, as shown below:

void validar_DATA()throw (invalid_argument){
   string num= "20/09/2020"; 
   int dia,mes,ano;
   stringstream aux;

   aux << num << endl;
   aux >> dia;

}

If it is printed day, the first two values come out(20), but how would I get the MONTH and the YEAR? The way I did, when reading the string to transform into int, when it gets to some character that is not number, in the case shown here is the '/', it stops reading, making only the two before it is transformed into int. Is there any way to read after the bar? Put some pointer to mark where it stopped and continue from the '/' ?

I thought of concatenating too, but I don’t know concatenate int.

1 answer

1

Since vc has a fixed date format ("DD/MM/YYYY"), I believe this is the simplest solution.

#include <string>
#include <iostream>

int main()
{
    std::string data = "20/09/2020";
    std::string dia_str = data.substr(0, 2);
    std::string mes_str = data.substr(3, 2);
    std::string ano_str = data.substr(6, 4);

    int dia = std::atoi(dia_str.c_str());
    int mes = std::atoi(mes_str.c_str());
    int ano = std::atoi(ano_str.c_str());

    std::cout << dia << "/" << mes  << "/" << ano;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.