Reputation: 21
So I've been set a task to create a temperature converter in C++ using this equation:
Celsius = (5/9)*(Fahrenheit – 32)
and so far I've come up with this (I've cut out the 10 lines worth of comments from the start so the code posted begins on line 11, if that makes any sense)
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main ()
{
float celsius;
float farenheit;
std::cout << "**************************" << endl;
std::cout << "*4001COMP-Lab5-Question 1*" << endl;
std::cout << "**************************" << endl << endl;
std::cout << "Please enter a temperature in farenheit: ";
std::cin >> farenheit >> endl;
std::cout << "Temperature (farenheit): " << endl;
std::cout << "Temperature (celsius): " << celsius << endl;
std::cin.get();
return 0;
}
Everytime I try to run this program I get a heap of errors with this one appearing every time:
1>m:\visual studio 2010\projects\week 5\week 5\main.cpp(26): error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::basic_istream<_Elem,_Traits>' (or there is no acceptable conversion)
I've tried everything I can think of to get rid of this error but it reappears every time, any idea on how to fix this?
Upvotes: 2
Views: 754
Reputation: 3346
std::cin >> farenheit >> endl;
This statement is invalid. remove >> endl
from it.
std::cin >> farenheit ;
This statement is only valid when you cout
something. Like here.
std::cout << farenheit << endl ;
The reason is that endl
is the end-line character used to output a new line. So only the output stream accepts it. You can look up more about return values and prototypes of cin
and cout
here.
http://en.cppreference.com/w/cpp/io
Upvotes: 9
Reputation: 31445
std::endl
is actually a function and the operator to stream into it is not defined. Yes it's a confusing error message as it is complaining about the LHS not the RHS.
Its implementation is something like:
namespace std {
std::ostream& endl( std::ostream& os )
{
os << '\n';
os.flush();
return os;
}
}
Streaming has then defined something like this:
namespace std {
std::ostream & operator<<( std::ostream & os, (std::ostream& *)(std::ostream&) func )
{
return func(os); // or is it (*func)(os)
}
}
It's actually quite a "powerful" feature of iostream, because you can then write a function with that signature and stream the function into your stream to do stuff with the iostream.
That is in fact a similar concept as to how the <iomanip>
library also works (although that uses objects).
Upvotes: 3