LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-20-2004, 05:20 AM   #1
chuanyung
LQ Newbie
 
Registered: Jan 2004
Posts: 25

Rep: Reputation: 15
[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.

Best Regards,
Chuanyung.
 
Old 07-20-2004, 09:22 AM   #2
spacer
LQ Newbie
 
Registered: Apr 2004
Location: Somewhere in Space
Distribution: RedHat
Posts: 10

Rep: Reputation: 0
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;

Hope it helps u
 
Old 07-20-2004, 09:31 AM   #3
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: Debian
Posts: 2,536

Rep: Reputation: 111Reputation: 111
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.
 
Old 07-20-2004, 10:37 AM   #4
Tesl
Member
 
Registered: Jun 2003
Location: Durham, UK
Distribution: Slackware 9, Mandrake 9.1
Posts: 163

Rep: Reputation: 30
Could you accept both the inputs, and then in the function that uses them surround it with a try{ catch{ block; and catch the input error that way?

There might be better ways of doing it, but iv always found exception handling really helpful for things like that
 
Old 07-20-2004, 11:10 AM   #5
dakensta
Member
 
Registered: Jun 2003
Location: SEUK
Distribution: Debian & OS X
Posts: 194

Rep: Reputation: 35
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;

}
 
Old 07-20-2004, 08:31 PM   #6
chuanyung
LQ Newbie
 
Registered: Jan 2004
Posts: 25

Original Poster
Rep: Reputation: 15
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.
 
Old 07-20-2004, 08:37 PM   #7
chuanyung
LQ Newbie
 
Registered: Jan 2004
Posts: 25

Original Poster
Rep: Reputation: 15
Quote:
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.
 
Old 07-21-2004, 04:11 AM   #8
dakensta
Member
 
Registered: Jun 2003
Location: SEUK
Distribution: Debian & OS X
Posts: 194

Rep: Reputation: 35
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.

HTH
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Ctrl+Shift Unicode input gone, after installing Japanese Input Methodes polemon Linux - Newbie 1 09-20-2005 05:17 PM
How to judge the linux os is 32 or 64? guduke Linux - Software 1 09-20-2005 07:11 AM
how to judge an IP is an indepedent true Internet IP? htic22 Linux - Newbie 1 04-24-2004 10:01 PM
A little question (maybe stupid, judge by ourselves) about DDR400 modules ParticleHunter General 2 04-16-2004 12:17 PM
<input type="button" disabled="true" > does not work in ns4.7 or 4.9 cybercop12us Programming 2 11-29-2002 08:31 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:36 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration