3
I’d like to convert a string
passed to type value double
.
Example:
string expressao = "1+1";
double x, y;
Such that, x = expressao[0];
and y = expressao[1];
And the sum of x+y
return 2 in response.
I’ve read some things about atof
, but I couldn’t apply it properly.
Follow the code below:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
double resultado(string); // prototipo
int main()
{
string expressao;
cout << "Exemplo de Expressão:\n\n1+2\n\n";
cout << "Insira uma expressão:";
getline(cin, expressao);
cout << expressao << " = " << resultado(expressao) << endl;
}
double resultado(string valor) {
double x, y;
/*
gostaria de recuperar apenas os valores numericos. Por exemplo:
Se a minha entrada for 1+1
gostaria repartir a entrada(1+1) em duas partes.
1. valor[0] para recuperar o valor 1
2. valor[1] para recuperar o outro valor 1 depois do sinal(+)
3. em seguida gostaria de converter esses dois char(valor[0] e valor[1]) em valores do tipo double par assim, somá-los e retorná-los.
*/
return x;
/*
if (opr[1] == '+') {
return x+y;
} else if (opr[1] == '-') {
return x-y;
} else if (opr[1] == '*') {
return x*y;
} else if (opr[1] == '/') {
return x/y;
} else {
return 0.0;
}
*/
}
I would like to double convert these two parts recovered through the string. double x, y; string expression = "1+1"; // input x = expression[0]; // value 1 which is in char y = expression[1]; // value 2 which is in char understands me?
– Ten. Oliveira
Post the part of how you are recovering the parts, to facilitate.
– Bacco
Yes, you can see that the problem is very different from the initial question. Here’s how to format your question: http://answall.com/markdown
– Bacco
I posted a photo now to help. The goal is to catch two chars from a string, convert these chars into doubles and then add them up.
– Ten. Oliveira
thanks for the tip Bacco... looking here.
– Ten. Oliveira
Actually it is preferable the code in text than the printscreen, but reading this help makes it easy you adapt.
– Bacco
I couldn’t edit it all :/
– Ten. Oliveira
Leave 4 spaces before each line of code, which is cool. It has the button
{ }
that already does it automatically. Select the part that is code and press the{ }
– Bacco
That’s it. Now I’ve got it
– Ten. Oliveira
You can view on http://answall.com/posts/18807/revisions. who actually managed to edit. I hope you can do it next time.
– Maniero
Ahh... rsrs thanks bigown and Bacco :)
– Ten. Oliveira