Here is an explanation (as in the tutorial) of what the example code was supposed to do:
As a rather contrived example, how would we write a for loop that outputs every number from 1 to 100
, but stops if the user enters the letter q? We could easily do it with a while loop, and use what we learnt above to make it quite small, but lets do it in a for loop
When I run it, I get an error "No match for 'operator=='..."
. Now I researched on the net and on SO itself, but all just seem to have advanced answers involving concepts which I have not yet learned.
I have provided the code and also some of the links where I researched. On one of the sites it says that "Yes, basically in C you can't use ==
to compare strings". On another site they spoke about overloading operators, which I also then researched, but that just confused me even more. On a similar problem here on SO one guy suggested using double quotes instead of single quotes, but I knew that would not work in my case since I used a char
and not a const char
or string
. And I ran it and my suspicions were confirmed. It gave an error: "Invalid conversion from const char to char"
So basically my question is this:
What is wrong with this code used in the tutorial, and what are the alternatives to prevent getting an error?
#include <iostream>
int main()
{
int i = 0;
char input = ' ' ;
for (i=1; i<=100; ++i)
{
if ((std::cin >> input) == 'a')
{
break;
}
}
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…