在 c++ 中使用字符串时出错。error C2679:二进制'<<':未定义采用类型为"类"的右操作数的运算符

Error when using strings in c++.error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class

本文关键字:lt 类型 运算符 操作数 未定义 字符串 C2679 error 二进制 c++ 出错      更新时间:2023-10-16

我第一次使用不同的函数创建C++程序,但每当我尝试使用字符串时,就会发生这种情况!

我只发布相关部分。

#include<string>
#include<iostream.h>
#include<math.h>
#include<cctype>

using namespace std;
..... (Skipping irrelevant parts)
<Variables go here.>
..... (Skipping irrelevant parts)
    if (tolower(from) == 'a')
    {
        unit = "Seconds";
        secondsto();
    }
    else if (tolower(from) == 'b')
    {
        unit = "Minutes";
        minutesto();
    }
    else if (tolower(from) == 'c')
    {
        unit = "Hours";
        hoursto();
    }
    else if (tolower(from) == 'd')
    {
        unit = "Days";
        daysto();
    }
/*  else if (tolower(from) == 'e')
    {
        unit = "Weeks";
        weeksto();
    }*/
    else if (tolower(from) == 'f')
    {
        unit = "Months";
        monthsto();
    }
    else if (tolower(from) == 'g')
    {
        unit = "Years";
        yearsto();
    }
    ..... (Skipping irrelevant parts)
if (tolower(from) == 'a')
    {
        unit = "Seconds";
        secondsto();
    }
    else if (tolower(from) == 'b')
    {
        unit = "Minutes";
        minutesto();
    }
    else if (tolower(from) == 'c')
    {
        unit = "Hours";
        hoursto();
    }
    else if (tolower(from) == 'd')
    {
        unit = "Days";
        daysto();
    }
/*  else if (tolower(from) == 'e')
    {
        unit = "Weeks";
        weeksto();
    }*/
    else if (tolower(from) == 'f')
    {
        unit = "Months";
        monthsto();
    }
    else if (tolower(from) == 'g')
    {
        unit = "Years";
        yearsto();
    }

...... (Skipping)
        cout << original_value << " " << unit << " --> " << value << " " << new_unit;

错误正是

error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no a
cceptable conversion)

我几乎尝试了我能找到的所有其他解决方案,但都没有成功。

不要在程序中包含不推荐使用的iostream.h,而是包含<iostream>。此外,switch将比级联if/else:更可读,并消除代码重复

switch ( tolower(from) ) {
   case 'a' :
      unit = "Seconds";
      secondsto();
      break;
   case 'b' :
      unit = "Minutes";
      minutesto();
      break;
     ...
 }

您还可以消除对tolower()函数的多次调用。

您需要更换

#include <iostream.h>

带有

#include <iostream>

你也应该尽量避免

using namespace std;

并使用

using std::cout;

std::cout << original_value << " " << unit << " --> " << value << " " << new_unit;