错误:在标准运算符>>< char中没有匹配“operator ==” [英] Error: No match for 'operator==' in standard operator>><char

查看:223
本文介绍了错误:在标准运算符>>< char中没有匹配“operator ==”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个解释(如在教程中)示例代码应该做什么:


,我们如何编写一个for循环,输出每个数字从1到100 ,但如果用户输入字母q,则停止?我们可以很容易地使用while循环,并使用我们上面学到的,使它相当小,但让它在一个for循环


当我运行它,我得到一个错误没有匹配的'operator =='...。现在我研究了网络和SO本身,但所有只是似乎有涉及概念,我还没有学到的高级答案。



我提供了代码,一些我研究的链接。在其中一个网站上,它说是的,基本上在C可以' t使用 == 比较字符串。在其他网站他们谈到超载运营商,我也研究了,但是只是困惑我更多。在 SO类似的问题上,一个人建议使用双引号,而不是单引号,但我知道这不会在我的情况下工作,因为我使用 char 而不是 const char string 。我跑了,我的怀疑证实了。它给出一个错误:从const char到char的转换无效



所以基本上我的问题是: / p>

本教程中使用的代码有什么问题,以及可以防止出现错误的替代方法是什么?

  #include< iostream> 

int main()
{
int i = 0;
char input ='';
for(i = 1; i <= 100; ++ i)
{
if((std :: cin>> input)=='a')
{
break;
}

}

return 0;
}


解决方案

  std :: cin>>输入; 

返回对 std :: cin 这不奇怪,不能与 char 比较。您可能想要

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

或更好,

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

$ b b

如果读取输入失败,它也会中断。


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;
}

解决方案

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.

这篇关于错误:在标准运算符&gt;&gt;&lt; char中没有匹配“operator ==”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆