Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

New to c++ - how to check if input is float or string ?

Status
Not open for further replies.

access97to2000

Programmer
Aug 12, 2002
45
US
Hi,
I have a question regarding input checking.
I want the user to enter 10 float type numbers. (10 maximum) he can stop entering the numbers instead of entering all 10 numbers by typing "End". I am taking n as float

how can I check if the entered value is "end" ? I am attaching the program down.

Thanks for your help


**************************************
float n;

cout << &quot;Hi Start Inputting the values (10# Max - Enter 'end' to End) \n\n\n&quot; ;

for (i=0;i<10;i++)
{
cout << &quot;Enter No &quot; << i+1 << &quot; : &quot; << &quot; &quot; ;
cin >> n;

if (n == &quot;end&quot;)
{
cout << &quot;Do you want to end enterning the numbers?(Y/N) ? &quot;;
cin >> ans;

}
 
Hi,
if you can use CString Class , you can use the following
method :
Code:
#include &quot;stdafx.h&quot;
#include &quot;afx.h&quot;
#include &quot;iostream.h&quot;
#include &quot;string.h&quot;

int main(int argc, char* argv[])
{

  int i;
  char ans;
  CString inputStr;
  char n[50];

  cout << &quot;Hi Start Inputting the values (10# Max - Enter 'end' to End)  \n\n\n&quot; ;

  for (i=0;i<10;i++)
  {
    memset(n,0,sizeof(n));
    cout << &quot;Enter No &quot; << i+1 << &quot; : &quot; << &quot; &quot; ;
    cin >> n;

	inputStr = n;
	if(inputStr.FindOneOf(&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~[]{}-_=+\\|'/?>,<&quot;) !=-1)
    {
	  if(inputStr == &quot;end&quot;) 
	  {
        cout << &quot;Do you want to end enterning the numbers?(Y/N) ? &quot;;
        cin >> ans;
		if(ans == 'Y' || ans == 'y')
		  break;
	  }
	  cout << &quot;input value must be numeric \n&quot;;
	  i--;
	}
  }
  
  return 0;
}
 
you could try this, (a bit easier than trying to use CString)

char* n;
cout << &quot;Hi Start Inputting the values (10# Max - Enter 'end' to End) \n\n\n&quot; ;

for (i=0;i<10;i++)
{
cout << &quot;Enter No &quot; << i+1 << &quot; : &quot; << &quot; &quot; ;
cin >> n;

if (n == &quot;end&quot;)
{
cout << &quot;Do you want to end enterning the numbers?(Y/N) ? &quot;;
cin >> ans;

}
else float new = atof(n);
 
Most importantly... you have to allocate some memory to n in Wiggis' example. Also, you cannot == strings, you have to use a function like strcmp, which returns 0 if the strings ar identical.

Vincent
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top