2016-09-26 74 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; 
}