Doubt in the use of the to_string function

Asked

Viewed 45 times

-1

In an exercise that I’m doing, it was proposed to read two numbers, an integer and a real, and count how many digits they have.

Entry and exit should be like this:

Entre com o numero inteiro: 2345

Entre com o numero real: 234.549

O numero inteiro possui 4 dígitos.

O numero real possui 6 dígitos.

I’m using this code to solve the problem:

//Entrada de numeros

cout << "Entre com o numero inteiro: ";
cin >> NumInt;
cout << "Entre com o numero real: ";
cin >> NumReal;
//Conversao para string
NumString = to_string(NumReal);

//Contador de digitos
while (NumString[i++] != '\0');

//Impressao do numero
cout << endl;   
cout << "Numero lido: " << NumString << endl;
cout << "Possui " << i - 1 << " digitos." << endl;

That’s the way out:

Entre com o numero inteiro: 1234

Entre com o numero real: 765.34

Numero lido: 765.340027

Possui 10 digitos.

Pressione qualquer tecla para continuar. . .

The real number is being read with extra digits. Could you help me?

  • What types of NumInt, NumReal and NumString? You can show your statements?

  • Yes, of course. int Numint; float Numreal; string Numstring;

1 answer

0

Increase the accuracy of NumReal replacing its type of:

float NumReal;

To:

double NumReal;
  • Thanks for the collaboration, I’ll test it here.

Browser other questions tagged

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