[C++] How do I judge the type of input is right or not?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
[C++] How do I judge the type of input is right or not?
Dear all,
I use C++'s cin to get data from screen.
If I want 1 string and 1 floating number,
but the input is not like above.
When this case appears, I must show a error.
How can I do ?
-------------------
string A;
float B;
cin >> A >> B;
/* then ??? */
--------------------
Thanks for your help.
Re: [C++] How do I judge the type of input is right or not?
Quote:
Originally posted by chuanyung Dear all,
I use C++'s cin to get data from screen.
If I want 1 string and 1 floating number,
but the input is not like above.
When this case appears, I must show a error.
How can I do ?
-------------------
string A;
float B;
cin >> A >> B;
/* then ??? */
--------------------
Thanks for your help.
Best Regards,
Chuanyung.
Anything cam be thought of as a string, so u cant actually check for it .
As reg float or not, u can typecast it to int n then check whether the both r same or not.
i.e int C = (int)B;
if (C==B)
then not float;
else float;
You may want to use strtod() for conversion. Read the "RETURN VALUE" section of its man -page on how to detect if a floating point number was correctly read.
If you provide input that cannot be formatted into required type, for example you send "Hello" to cin >> a_float; then you will find that cin.fail() returns true.
You can also put your input into a 'while' statement which will implicitly cast the returned stream to void* and thus a bool test.
For reading a string, you might want to think about std::getline, rather than cin >> a_string; as this lets you use whitespace in the string and will remove the terminating '\n', if you want to.
N.B. This does depend on the type of input you expect ... from the screen I would expect a prompt before each data input and to hit 'return' after typing the desired data, from a file (or piped file) I would expect different, maybe whitespace delimited columns which would require a slightly different strategy, (like reading the whole lot into a string as suggested above) so post back if you have a particular input format and get stuck. I would tend to use istringstream's to convert strings into other datatypes but feel free to use whatever you like.
Example:
Code:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
float f;
string s1;
cout <<"Enter string\n";
// Assume this function will work, pretty rare not to ...
getline(cin, s1)
cout << "Enter float\n";
// Until we get good input, keep trying ...
while (!(cin >> f))
{
// Error message
cout << "Float input failed\nEnter float\n";
// clear the failbit set by bad input
cin.clear();
// We probably still have bad input lying in the stream
// so we need to dispose of it
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Data Entered " << s1 << " and " << f << endl;
}
Re: Re: [C++] How do I judge the type of input is right or not?
Quote:
Originally posted by spacer Anything cam be thought of as a string, so u cant actually check for it .
As reg float or not, u can typecast it to int n then check whether the both r same or not.
i.e int C = (int)B;
if (C==B)
then not float;
else float;
Hope it helps u
This has a bug when input is such as 10.0 .
10.0 will be not a float number.
Originally posted by dakensta If you provide input that cannot be formatted into required type, for example you send "Hello" to cin >> a_float; then you will find that cin.fail() returns true.
You can also put your input into a 'while' statement which will implicitly cast the returned stream to void* and thus a bool test.
For reading a string, you might want to think about std::getline, rather than cin >> a_string; as this lets you use whitespace in the string and will remove the terminating '\n', if you want to.
N.B. This does depend on the type of input you expect ... from the screen I would expect a prompt before each data input and to hit 'return' after typing the desired data, from a file (or piped file) I would expect different, maybe whitespace delimited columns which would require a slightly different strategy, (like reading the whole lot into a string as suggested above) so post back if you have a particular input format and get stuck. I would tend to use istringstream's to convert strings into other datatypes but feel free to use whatever you like.
Example:
Code:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
float f;
string s1;
cout <<"Enter string\n";
// Assume this function will work, pretty rare not to ...
getline(cin, s1)
cout << "Enter float\n";
// Until we get good input, keep trying ...
while (!(cin >> f))
{
// Error message
cout << "Float input failed\nEnter float\n";
// clear the failbit set by bad input
cin.clear();
// We probably still have bad input lying in the stream
// so we need to dispose of it
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Data Entered " << s1 << " and " << f << endl;
}
This works almost well.
But
(a) if I want a realy float, input is a integer.
(b) if I want a realy integer,input is a float.
For these 2 cases, cin.fail() is always return false.
So it seems not to check perfectly.
I am not sure I quite follow but this is what I think you are saying is that you want to determine a float by the presence of a decimal point.
So, for the statement (using float f):
cin >> f;
input:
a) 12.34
b) 12
a) is acceptable to you because it has a decimal point, b) is not because there is no decimal point.
To c++ both are acceptable and you have a value of 12.34 or 12.0.
For the statement (using int i):
cin >> i
input:
a) 12.34
b) 12
a) is unacceptable because there is a decimal point, b) is acceptable because there is no decimal point.
To c++ BOTH are acceptable and i will take on the value 12. This is because, in both cases you have provided something that is convertable to an integer.
What you need to be aware of is that in a) you still have ".34\n" still waiting in the buffer.
The quick way to check this is write:
if (cin.peek() == '.') { //call error handler }
But, if you are going to require the presence of a decimal point, then you need to read in a string, validate the string and decide if you are going to accept it or not.
From a c++ point of view, it is not malformed input unless the supplied input CANNOT be converted into the desired type.
An int 12 from 12.34 is c++ 'best guess'.
A float 12 from input 12 is still a float despite no decimal point being supplied.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.