试图使用stringstream将字符串转换为整型

Trying to convert a string into a int using stringstream

本文关键字:字符串 转换 整型 stringstream      更新时间:2023-10-16

我正在尝试检查字符串表示是否等于给定整数。我打算在函数中使用stringstream。我也有一个operator=

我有点困惑如何执行这些在一起,如果我错过了什么。这是我的最后一个作业,这只是我整个程序的一小段。我找不到很多关于这方面的指南,我感觉它们都指引我去一个我不允许使用的地方。

#ifndef INTEGER
#define INTEGER
using std::string;
class Integer
{
private:
    int intOne;
    string strOne;
public:
    Integer() {
        intOne = 0;
    }
    Integer(int y) {
        intOne = y;
    }
    Integer(string x) {
        strOne = x;
    }
    void equals(string a);  
    Integer &operator=(const string*);
    string toString();
};
#endif 

在这个头文件中,我不确定=操作符应该使用什么参数。

#include <iostream>
#include <sstream>
#include <string>
#include "Integer.h"
using namespace std;
Integer &Integer::operator=(const string*)
{
    this->equals(strOne);
    return *this;
}
void Integer::equals(string a)
{
    strOne = a;
    toString(strOne);
}
string Integer::toString()
{
    stringstream ss;
    ss << intOne;
    return ss.str();
}

 #include <iostream>
#include <cstdlib>
#include <conio.h>
#include <string>
#include <ostream>
using namespace std;
#include "Menu.h"
#include "Integer.h"
#include "Double.h"

int main()
{
    Integer i1;
    i1.equals("33");
    cout << i1;
}

很抱歉,如果这是一个不好的问题,我不太熟悉这种类型的作业,我会接受任何帮助,我可以得到。谢谢。

您可以使用std::to_strig(),让您从int转换为表示相同数字的字符串

因此,如果我理解正确,您想重载操作符=,这是一个坏主意,因为operator=用于赋值而不是用于比较。

正确的操作符签名是:

ReturnType operator==(const TypeOne first, const TypeSecond second) [const] // if outside of class
ReturnType operator==(const TypeSecond second) [const] // if inside class

因为你不能比较字符串和整数(它们是不同的类型),你需要写你的比较函数,因为你没有一个,我会为你写一个:

bool is_int_equal_string(std::string str, int i)
{
    std::string tmp;
    tmp << i;
    return tmp.str() == i;
}

最后但同样重要的是,您需要将这两个操作符合并为一个方便的操作符:

// inside your Integer class
bool operator==(std::string value) const
{
    std::stringstream tmp;
    tmp << intOne;
    return tmp.str() == ref;
}

现在可以像使用其他操作符一样使用这个操作符了:

Integer foo = 31;
if (foo == "31")
    cout << "Is equal" << endl;
else
    cout << "Is NOT equal" << endl;

如果您被允许使用std::to_string,那么它将是最好的。

否则,您可以使用std::stringstream创建一个函数来处理字符串和整数之间的相等性:

的例子:

bool Integer::equal(const string& str)
{
    stringstream ss(str);
    int str_to_int = 0;
    ss >> str_to_int;
    if (intOne == str_to_int)
        return true;
    else
        return false;
}

结合if语句:

int main()
{
    Integer i{100};
    if (i.equal("100"))
        cout << "true" << endl;
    else
        cout << "false" << endl;
}