Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c++ - Error: No match for 'operator==' in standard operator>><char

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
std::cin >> input;

returns a reference to std::cin which, unsurprisingly, cannot be compared to a char. You probably want

if (std::cin >> input && input == 'a')

or even better,

if (!(std::cin >> input) || input == 'a')

which will also break if reading input fails.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...