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.

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.

commented: thanks +1

Thanks for the answers guys.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.