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;

Were you trying to do a Null terminator check?

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

vs

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

Edited 3 Years Ago by mike_2000_17: Fixed formatting

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.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

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

This question has already been answered. Start a new discussion instead.