为什么此字符串操作不起作用?

时间:2020-03-23 21:53:48

标签: c++

代码如下:

#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”)|

如何解决此错误并使程序正确运行?

2 个答案:

答案 0 :(得分:1)

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;
}

答案 1 :(得分: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;
}