Hi, I'm working on a program to convert Celsius to Fahrenheit, but I have a problem when I run a check to make sure that input is not a letter. My problem is that if the user inputs a 0 it catches it with the

if(num == 0) {
		cout << "That was not a number!\n\n";
		}

So I tried changing it to this:

if(num == 0 && !(buf == "0")) {
		cout << "That was not a number!\n\n";
		}

but it still doesn't work, even when 0 is the only thing submitted! Any suggestions?

I think that it might be registering the enter as part of the string, but any advice to help this to work, or any advice on how this could be done better would be appreciated!

Below is my entire code.

// enter the temperature in celsius
	int nCelsius;
	int nIsANumber;
	char buf[256];

	nCelsius = 0;
	nIsANumber = 0;
	
	while(nIsANumber == 0)
	{
		// Ask for input here
		cout << "Enter the temperature in Celsius: \n";
		
		cin.getline(buf,256);
		int num = atoi(buf); // atoi returns 0 if it is invalid
		if(num == 0 && !(buf == "0")) {
		cout << "That was not a number!\n\n";
		}
		else {
			nCelsius = atoi(buf); 
			nIsANumber = 1;
		}
	}

	//Conversion factor for celsius to fahrenheit
	int nFactor;
	nFactor = 212 - 32;
	int nFahrenheit;
	nFahrenheit = nFactor * nCelsius/100 + 32;
	//output the results
	cout << "Fahrenheit temperature is:";
	cout << nFahrenheit;
	nCelsius = 0;

Recommended Answers

All 7 Replies

Were you trying to do a Null terminator check?

    if(num == 0 && !(buf == "0")) {

vs

    if(num == 0 || !*buf) {

Were you trying to do a Null terminator check?

    if(num == 0 && !(buf == "0")) {

vs

    if(num == 0 || !*buf) {

end quote.

I'm not positive what that means (I think it means if I were checking if it were empty vs. the string is simply zero)

I'm trying to check if the string is zero.

Or looking for an actual zero string?

if(num == 0 && strcmp(buf, "0")) {

I don't understand, you are saying if it equals zero then "it is not a number"? Also, you can use this std::string Zero = "0"; then if(Zero.compare(buf)) actually, i think compare() returns the edit distance, so you need to see if it equals 0, so more like if(Zero.compare(buf) == 0)

Or looking for an actual zero string?

if(num == 0 && strcmp(buf, "0")) {

It works! Thank you very much :D

Since you're using C++, use yours.

if (0 == strcmp( a, b) then the same
else not the same!

Solved thanks to wildgoose!

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.