c++ - 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;
}
这是我得到的错误
解决方案
在这些声明中:
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();
否则,将int
s 转换为std::string
using 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);
推荐阅读
- c# - 将动态创建的用户控件图像和文本高度绑定到网格单元高度 WPF
- c++ - 从 C++ dll 调用 Go dll
- c - 警告:函数“colcheck”的隐式声明 [-Wimplicit-function-declaration]
- html - 最小窗口网页设计
- wordpress - Woocommerce 结帐客户条件
- javascript - 为什么要在 Node js 中使用消息队列?
- python - 如何为 nlp 任务清理 20newsgroup 数据集
- python - 模块化 PyTest
- c - void* 与 char* 具有相同的表示和内存对齐是什么意思?
- python - 如何定义输入为列名的函数?