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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing right value to the function 1

Status
Not open for further replies.

rakeshou

Programmer
Aug 15, 2006
17
US
I have a function that receives the integer values :
void link::add(int val)
{

node1 *q,*temp;
q = new node1;
if(node==NULL)
{
node = new node1;
node->data=val;
node->next=NULL;

}

else
{
q=node;
while(q->next != NULL)
{
q = q->next;

}
temp = new node1;
temp->data=val;
temp->next=NULL;
q->next = temp;
}

temp=node;
while(temp!=NULL)
{
cout<<temp->data<<" -> ";
temp=temp->next;
}

}


but if the user inputs a character instead of an int, the programms goes into infinite loop:

above function is called as:
link list; //object of link class
int val;
cin>>val;
list.add(val); //call above funciton


any ideas what to do...



 
Validate your input before trying to use it. If the user doesn't enter a number, print an error and tell them to try again.
 
You could read the input into a string, then call atol() and ltoa(). If the result of ltoa isn't equivalent to the original input, they put in some kind of garbage!
 
or you can use C++ and do it this way:
Code:
#include <iostream>
#include <string>
#include <sstream>

using namespace std;


int main( int argc, char* argv[] )
{
	int i;
	stringstream ss;

	do
	{
		ss.clear();
		ss.str( "" );	// Clear the stringstream.

		cout << "Enter a number: " << endl;
		string str;
		getline( cin, str );

		ss << str;
		ss >> i;

	} while ( ss.fail() == true );

	cout << "i = " << i << endl;

	return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top