首页 > 解决方案 > C++“表达式必须具有整数或无范围枚举类型”错误

问题描述

我试图为初学者编程课程做一些 C++ 作业,但我在代码中遇到了一个问题。作业说:

创建一个程序,要求用户输入 2 个整数,然后指出第一个数字是否是第二个数字的倍数。(使用条件运算符在两个字符串中进行选择,并根据答案显示必要的一个)

#include <iostream>
using namespace std;

int main() {
    int n1;
    int n2;
    cout << "Enter a number: \n";
    cin >> n1;
    cout << "Enter another number:\n";
    cin >> n2;
   
   
    int residue = n1 % n2;                                      //Remains of the division
    cout << residue;
    bool isMultiple = residue == 0;
    string r1 = (n1 << "is a multiple of " << n2);
    string r2 = ( n1 << "is not a multiple of " << n2);
    string ans = isMultiple ? r1 : r2;
    cout << ans;
}

这是我得到的错误

带有行和错误的错误代码

标签: c++

解决方案


在这些声明中:

string r1 = (n1 << "is a multiple of " << n2);
string r2 = ( n1 << "is not a multiple of " << n2);

n1和 n2 是int变量。因此,对于r1,您正在调用按位<<左移运算符,首先使用int左操作数的 an 和右操作数的const char[](字符串文字),然后第二次使用左侧的结果和int右侧的 an。但是您根本无法int通过字符串文字移动 an,这将不起作用,这就是您收到编译器错误的原因。

然后你对 做同样的事情r2,所以你也会得到同样的错误。

您似乎正在尝试将格式化的输出存储到您的string变量中。你不能<<用来分配一个std::string这样的。使用 astd::ostringstream代替,例如:

#include <sstream>
#include <string>
using namespace std;

...

ostringstream oss;
oss << n1 << " is a multiple of " << n2;
string r1 = oss.str();

oss.str("");
oss << n1 << " is not a multiple of " << n2;
string r2 = oss.str();

否则,将ints 转换为std::stringusing std::to_string()(或等效),然后使用+连接运算符将它们连接起来,例如:

#include <string>
using namespace std;

...

string r1 = to_string(n1) + " is a multiple of " + to_string(n2);
string r2 = to_string(n1) + " is not a multiple of " + to_string(n2);

或者,使用std::format()(或{fmt} 库),例如:

#include <string>
#include <format> // or <fmt/core.h>
using namespace std;
//using namespace fmt;

...

string r1 = format("{} is a multiple of {}", n1, n2);
string r2 = format("{} is not a multiple of {}", n1, n2);

推荐阅读