2016-09-26 4 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

그래서 올바르게 이해한다면 이 비교 대상이 아니기 때문에 연산자 =에 과부하를 걸고 싶습니다. 잘못된 생각입니다.

올바른 운영자 서명은 : 당신이 (서로 다른 종류) 당신이 난 것 하나를 가지고 있지 않기 때문에, 당신이 당신의 comparisment 기능을 쓸 필요가 정수로 문자열을 비교할 수 없기 때문에

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

당신을 위해 하나를 쓰기 :

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

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

마지막으로, 당신은 하나의 편리한 조작으로, 그 둘을 병합해야

이제 당신은 다른 모든 것처럼,이 연산자를 사용할 수 있습니다

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

도움이 되었기를 바랍니다.

0

std::to_string을 사용하는 것이 허용되면 가장 좋을 것입니다.

예 :

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 문이 결합 :

그렇지 않으면, 당신은 문자열과 std::stringstream의 사용과 정수 사이의 평등을 처리하는 함수를 만들 수 있습니다

int main() 
{ 
    Integer i{100}; 

    if (i.equal("100")) 
     cout << "true" << endl; 
    else 
     cout << "false" << endl; 
} 
관련 문제