错误 C2678:二进制">>":找不到采用类型为"std::basic_istream<_Elem,_Traits>"的左操作数的运算符

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::basic_istream<_Elem,_Traits>'

本文关键字:gt Elem lt istream 运算符 操作数 Traits 找不到 二进制 C2678 std      更新时间:2023-10-16

我收到这个奇怪的错误。我想我已经包含了所有必要的文件。什么原因可能导致这种情况?错误是由以下行引起的:

cin >> x >> "n" >> y >> "n";

这是代码:

#ifndef ARITMETICE_H
#define ARITMETICE_H
#include <iostream>
#include <string>
#include "UIcomanda.h"
using namespace Calculator::Calcule;
namespace Calculator{
namespace UI{
    template<int Operatie(int, int)>
    class CmdAritmetice : public ComandaCalcule
    {
    public:
        CmdAritmetice(const string &nume) : ComandaCalcule(nume)
        {
        }
        void Execute()
        {
            cout << Nume() << "n";
            cout << "Introduceti doua numere intregi (x, y)n";
            int x, y;
            cin >> x >> "n" >> y >> "n";   // here a get the error
            cout << x << " " << Nume() << " " << y << " = " << Operatie (x,y) <<"n";
        }
    };
}
}
#endif

问题是cin >> "n" .它旨在将用户输入读取为字符串文字,这没有任何意义。只需删除它,将其设为cin >> x >> y;

不确定当您尝试将数据从流中提取到字符串文本中时会发生什么!

cin>> 必须在右侧有一个可写变量,你 cin>>""将 CIN 重定向到常量字符* 类型,该类型是只读的

总之,只需使用cin>>x>>y;iostream将为您完成其余的工作。

cinistream 类型的对象。此类重载了运算符>>,用于从控制台获取输入并将值放入给定变量中。变量必须是 l 值,而不是 r 值。简而言之,>>右侧给出的表达式必须是可写变量。

这将不起作用:

const int x;
cin >> x;

仅仅因为x是一个const int&,而不是istream::operator>>(int&)所期望的int&

更进一步,当您拨打电话时:

cin >> "n";

您实际上是在调用operator >> (const char*)而不是operator >> (char*),因此会出现错误。由于 operator>> 和模板代码的多个重载,错误不清楚。

注意operator >>的确切签名可能有所不同,但问题在于恒定性。

如果你打算使用空格和一个换行符(注意新行表示的风格),你可以写一个操纵器

#include <cctype>
#include <iostream>
#include <sstream>
std::istream& nl(std::istream& is) {
    typedef std::istream::traits_type traits;
    while(true) {
        traits::int_type ch;
        if(std::isspace(ch = is.get())) {
            if(ch == 'n') break;
        }
        else {
            is.putback(ch);
            // No space and no 'n'
            is.setstate(std::ios_base::failbit);
            break;
        }
    }
    return is;
}
int main()
{
    std::istringstream s("1n2");
    int x, y;
    s >> x >> nl >> y >> nl;
    std::cout << x << ' ' << y << 'n';
    if(s.fail()) {
        // The missing 'n' after '2'
        std::cout <<"Failuren";
    }
    return 0;
}