WhattayaBrian wrote:Can you say what didn't work for you? Because, unless I typed something wrong, this is very standards compliant, essentially boilerplate code.
Oh, I just made little test, and got true results:
Reasons, why std::cin will works wrongly: if you will type wrong characters after degits (for example 578gwr will cause error)
if you will type "g542", the "fail()" will works.
Testing code:
Code: Select all
#include <iostream>
int main()
{
double test;
std::cout<<"First cin!\n";
std::cin >> test;
if(std::cin.fail())
std::cout<<"You sucks!\n";
else
std::cout<<"Yur text is\n"<<test;
std::cin.clear();
std::cout<<"Second cin!\n";
std::cin >> test;
std::cin.clear();
std::cout<<"Third cin!\n";
std::cin >> test;
return 0;
}
and result (MinGW Windows):
Code: Select all
T:\root\cpp>g++ dummy.cpp -o dummy.exe
T:\root\cpp>dummy
First cin!
24gh
Yur text is
24Second cin!
Third cin!
T:\root\cpp>
result (GCC Linux)
Code: Select all
[root@whl-sr-001 cpp]# g++ dummy.cpp -o dummy
[root@whl-sr-001 cpp]# ./dummy
First cin!
466.57
Yur text is
466.57Second cin! //Accepted, value is right
45/234^H^H^H
Third cin! //Hey! this should be wrong!, stinky cin!
//third cin skipped by broken cin
[root@whl-sr-001 cpp]# ./dummy
First cin!
24f
Yur text is //Hey! this should be wrong!, stinky cin!
24Second cin! //skipped by broken cin
Third cin! //skipped by broken cin again
[root@whl-sr-001 cpp]#
Anyway, this will work stable:
Code: Select all
#include <iostream>
#include <stdio.h>
#include <string.h>
double StrToDouble(std::string in, bool*ok=NULL)
{
if(in.empty())
{
if(ok) *ok=true;
return 0.0;
}
double value;
bool dot=false;
for(int i=0;i<in.size();i++) //If you wish have less code - use regex, but this manual check works too
{
if(!isdigit(in[i]))
{
if((i==0)&&((in[i]=='-')||(in[i]=='+')))
continue;
else
if((in[i]=='.')&&(!dot))
{
dot=true;
continue;
}
else
{
if(ok) *ok=false;
return 0.0;
}
}
}
sscanf(in.c_str(), "%lf", &value);
if(ok) *ok=true;
return value;
}
int main()
{
double value=0;
char op;
std::string tmp;
retrychar:
tmp.clear();
std::cout <<"type one char:\n";
std::cin >> tmp;
if(tmp.size()!=1)
{
std::cout << "Wrong number of characters! type only one!\n"; goto retrychar;
}
op = tmp[0];
std::cout << "You typed character '"<< op <<"'\n\n";
std::cout <<"Now type floading point number:\n";
retrydouble:
tmp.clear();
std::cin >> tmp;
bool ok=false;
value = StrToDouble(tmp, &ok);
if(!ok)
{
std::cout<<"Wrong value, should be floating point! Try again!\n";
goto retrydouble;
}
std::cout << "You typed string '"<< tmp <<"'\n\n";
std::cout << "You typed number '"<< value <<"', hm, I forgot to use the iomanip.h, but anyway\n";
printf("with printf I can manupulate without 'iomanip.h'! :D, enjoy: %.8lf\n\n", value);
return 0;
}
this thing always sends a string data and cin will never crashed and you will anyway have able to type any values