【问题标题】:expression must have arithmetic or unscoped enum type C++ [duplicate]表达式必须具有算术或无范围枚举类型 C++ [重复]
【发布时间】:2020-11-01 09:52:48
【问题描述】:

我正在尝试使用 C++ 进行密码提示。我的代码如下:

#include <iostream>
#include <string>
std::string operator * (std::string a, unsigned int b) {
    std::string output = "";
    while (b--) {
        output += a;
    }
    return output;
}
int main(){
    std::string pword;
    std::string user;
    std::cout << "Enter username: ";
    std::cin >> user;
    std::cout << "Enter password for user '" << user << "': ";
    std::cin >> pword;
    std::string pword_asterix = ("*") * pword.length();  // ERROR
    std::clog << "Noted user '" << user << "' and password '" << pword_asterix << "'.";

但我从 Visual Studio Code 收到以下错误:

表达式必须具有算术或无范围枚举类型(第 17 行)

我该怎么办?

【问题讨论】:

  • 你到底想在这里做什么:std::string pword_asterix = ("*") * pword.length();?
  • std::string pword_asterix = std::string("*") * pword.length();
  • @πάνταῥεῖ 我试图将一个字符串相乘。

标签: c++ visual-studio-code


【解决方案1】:

 std::string pword_asterix = ("*") * pword.length();

你乘以一个指针,你想要这样的东西:

std::string pword_asterix(pword.length(), '*');

之后:

pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
Enter username: aze
Enter password for user 'aze': qsdqsd
Noted user 'aze' and password '******'.pi@raspberrypi:/tmp $ 

添加 &lt;&lt; std::endl 拥有

std::clog << "Noted user '" << user << "' and password '" << pword_asterix << "'." << std::endl;` 

在 shell 中使输出更清晰:

pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
Enter username: aze
Enter password for user 'aze': qsdqsd
Noted user 'aze' and password '******'.
pi@raspberrypi:/tmp $ 

【讨论】:

  • 我不知道你为什么建议 std::string("*") * pword.length() 解决问题。
  • @cigien 你是对的,很奇怪,因为我试过了......或者我错过了编译?我编辑了我的答案
  • @cigien 我喜欢 c++ 并且是我的主要语言,但显然 python 对用户更友好并且允许这样做。感谢您警告我错误的解决方案
  • 我理解这种观点; python 有时会更容易使用,我不同意这一点。就个人而言,我发现 C++ 中静态类型检查的价值远远超过了易于编码的好处。它确实取决于上下文,当然,人们可能会选择哪种语言。
  • 是的,我一直喜欢 C++,但在过去的 5-10 年里,我已经成长为喜欢它,因为它是以使写作更容易,更有趣的方式不断发展:)
【解决方案2】:

在第 17 行你有这条线

("*") * pword.length();

T(*) = std::string"T(pword.length()) = int。 我们可以在文档中找到字符串不能相乘(不支持运算符*):http://www.cplusplus.com/reference/string/string/string/

如果您尝试使用length = pword.length() 构造字符串并使用*s 进行初始化,请查看文档中的“填充构造函数”。在您的情况下,它将是:

std::string pword_asterix(pword.length(), '*');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多