2016-09-26 27 views
1

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

我有点困惑如何一起执行这些,如果我失去了一些东西。这是我的最后一项任务,这只是我整个计划的一小部分。在这方面我找不到很多指导,我感觉他们都指导我atoi或atod,这是我不允许使用的。

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

对不起,如果它的一个坏问题我不太熟悉这种类型的任务,并会采取任何帮助,我可以得到。谢谢。

回答

0

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

0

所以,如果我理解正确,你想超载运营商=,这是一个坏主意,因为operator=是用于分配而不是比较。

正确的操作签名是:

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

既然你不能比较两个字符串到整数(他们是不同类型的),你需要写你的comparisment功能,因为你没有一个我会写了一个给你:

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; 

我希望这有助于。

0

如果你被允许使用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; 
}