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)
{
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;``````
3
Contributors
7
Replies
8
Views
9 Years
Discussion Span
Last Post by Pokenerd

Were you trying to do a Null terminator check?

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

vs

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

Edited 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 by mike_2000_17: Fixed formatting

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!