954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Accept int but not char

Im doing a code "test" from the c++ book I am currently reading, the objective is to ask for input using a function and output data using a function, while keeping the data in main.

I finished it and it works, but I want to make the program not accept char's as input but accept int's, as a form of personal enrichment. :)

#include <iostream>

void info(int& x, char name [])
{
	std::cout<<"Enter a number, 0 to end: ";
	std::cin>>x;

	if((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'))
	{
		std::cout<<"\nPlease don't enter a letter\n";
		std::cout<<"I will convert it for you anyway: ";
		x = (static_cast<int>(x));
		std::cout<<x;
		
	} 

	if(x != 0)
	{
		std::cout<<"\nEnter a name, less than 15 characters: ";
		std::cin>>name;
	}

}

void output_data(const int x, const char name[])
{
	std::cout<<"\nThe name was: "<<name;
	std::cout<<"\nThe number was: "<<x<<"\n\n";
}

int main()
{
	int x(0);
	char name[15];
	for(;;)
	{
	info(x, name);
	if(!x)
	break;

	output_data(x, name);
	
	}
	return 0;
}


The problem is in the function named info, lines 8-13.
I want it to accept int's but not chars, i've tried a do-while loop but I cant find a way for the program to distinguish between a char and its ANSI representation. I hope its not an easy trick, I might have forgotten, I dont feel very good at the moment.

L3gacy
Light Poster
38 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 
Nandomo
Junior Poster
109 posts since Sep 2010
Reputation Points: 7
Solved Threads: 3
 

You need to read the input as a character string. Then look at the string and make sure every character is a digit. If so, convert to integer, if not display an error.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Thanks for the answers guys.

L3gacy
Light Poster
38 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: