【问题标题】:Why is this string operation not working?为什么这个字符串操作不起作用?
【发布时间】:2020-07-04 10:02:09
【问题描述】:

代码如下:

#include <cmath>
#include <iostream>

using namespace std;

int main()
{
    string sidelength;
    cout << "Perimeter of Square" << endl;
    cout << "Enter length of one side: ";
    getline(cin, sidelength);
    cout << sidelength * 4 << endl;

    return 0;
}

运行时,这是错误信息:

错误:'operator*' 不匹配(操作数类型为 'std::__cxx11::string {aka std::__cxx11::basic_string}' 和 'int')|

如何修复此错误并让程序正常运行?

【问题讨论】:

  • 如何将一串字符相乘?
  • error: no match for 'operator'* 表示未定义字符串相乘。
  • 你不能只输入一个整数吗?
  • int sidelength; cin &gt;&gt; sidelength; sidelength *= 4; cout &lt;&lt; sidelength &lt;&lt; endl;
  • 你是数字相乘,因此数据类型需要是intlongdouble,一些数字类型。

标签: c++


【解决方案1】:

如果你真的想把一个字符串乘以一个数字,你可以重载operator*

#include <cmath>
#include <iostream>
#include <cctype>
#include <string>

std::string operator*(const std::string &s,int x) {
    std::string result;
    try {
        result = std::to_string(stoi(s)*x);
    } catch(const std::invalid_argument&) {
        result="UND";
    }
    return result;
}

std::string operator*(const std::string &s,double x) {
    std::string result;
    try {
        result = std::to_string(stof(s)*x);
    } catch(const std::invalid_argument&) {
        result="UND";
    }
    return result;
}

int main()
{
    std::string input("1");
    input = input * 5.32;
    std::cout << input << std::endl;
    input = input * 2;
    std::cout << input << std::endl;
    return 0;
}

【讨论】:

    【解决方案2】:

    get line 函数将一个字符串作为它的第二个参数,但您希望获取一个整数/双精度/浮点数作为输入。所以不要使用getline。只需在下面运行此代码即可解决您的问题。

    #include <cmath>
    #include <iostream>
    using namespace std;
    
    int main()
    {
        int sidelength;
        cout << "Perimeter of Square" << endl;
        cout << "Enter length of one side: ";
        cin >> sidelength;
        cout << sidelength * 4 << endl;
        return 0;
    }
    

    【讨论】:

    • 顺便说一句,不需要包含cmath。
    猜你喜欢
    • 2012-11-30
    • 2022-01-26
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2016-05-17
    • 1970-01-01
    相关资源
    最近更新 更多