I need the program to accept only decimal numbers. The one I did is fine, only accepts decimals, but if you enter for example -23.45jdhsdj
. The numbers if you save them, although you ignore the letters and it should not be like that.
You should reject a number that contains lyrics in any part of it.
Here I leave what I have achieved so far:
#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
using namespace std;
bool funciondecimal(string);
int main()
{
string numero;
bool repite=true;
do{
cout<<"Dijite el numero: ";
cin>>numero;
if(!funciondecimal(numero)){
cout<<"tiene punto decimal"<<endl;
repite=false;
}else{
cout<<"No tiene punto decimal"<<endl;
}
}while(repite);
return 0;
}
bool funciondecimal(string numero){
bool resp= true;
for(int contador=1;contador<=numero.size();contador++){
if(numero[contador-1]=='.'|| numero[contador-1]==','){
resp=false;
break;
}
}
return resp;
}
PS: I was asked the question as a duplicate, but the one that currently exists and has a solution is for integers and I need it only for FLOAT, thanks Here the solution for integers in Stack Overflow
Here I leave the last improvement I made: no longer allows letters but still allowing characters (! @ # $% ^ & amp? *? < +), if someone has an idea of how to solve it would be great, thanks
#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
using namespace std;
bool funciondecimal(string);
int main()
{
string numero;
bool repite=true;
do{
cout<<"Dijite el numero: ";
cin>>numero;
if(funciondecimal(numero)){
cout<<"tiene punto decimal"<<endl;
repite=false;
}else{
cout<<"No tiene punto decimal"<<endl;
}
}while(repite);
return 0;
}
bool funciondecimal(string numero){
bool resp= false;
for(int contador=1;contador<=numero.size();contador++){
if((numero[contador-1]=='-'|| numero[contador-1]=='+') && (numero[contador]==','|| numero[contador]=='.')){
resp=true;
break;
}
}
for (int contador2=1;contador2<=numero.size();contador2++){
if((numero[contador2]>='0' && numero[contador2]<='9') && (numero[contador2]==','|| numero[contador2]=='.')){
resp=true;
}
}
for(int contador3=1;contador3<=numero.size();contador3++){
if(numero[contador3-1]==','|| numero[contador3-1]=='.'){
resp=true;
}
}
for(int contador4=1;contador4<=numero.size();contador4++){
for(int letra='a';letra<='z';letra++){
if(numero[contador4-1]==letra){
resp=false;
break;
}
}
for(int letra2='A';letra2<='Z';letra2++){
if(numero[contador4-1]==letra2){
resp=false;
break;
}
}
// if(numero[contador4-1]=='a'){
// resp=false;
// break;
//}
}
return resp;
}