2013-05-16 3 views
0

여기에 주석 행을 무시하는 코드가 있습니다. 문제는, 내가 가지고있는 것을 가진 함수를 만들려고했는데, 나중에 코드 내에서 그것을 사용할 수 있습니다. 하지만 문제가 발생했습니다. 내 코드 :str.erase(); 함수 내에서 작동하지 않습니다.

#include <iostream> 
#include <string> 

using namespace std; 
string comment(string str); 

int main() 
{ 
    string str; 
    cout << "Enter the string> "; 
    getline(cin, str); 
    comment(str); 
    cout << str << "\n"; 

    return 0; 
} 

string comment(string str) 
{ 

    unsigned found = str.find('#'); 
    if (found!=std::string::npos) 
    str.erase(found); 
    else 
    return(str);   

    return(str); 

} 

샘플 입력 : 내가 얻을 수 있겠

my name is #comment 

출력 : (키보드) 내 이름은 내가 무엇입니까 #comment

출력> 문자열을 입력합니다 : 내가 기능없이 동일한 코드를 사용하는 경우

my name is 

또한, 나는 정확한 답변을 얻을. 그리고 여기있다 : 당신은이

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    string str; 

    cout << "Enter the string> "; 
    getline(cin, str); 
    unsigned found = str.find('#'); 
    if (found!=std::string::npos) 
    str.erase(found); 


    cout << str << "\n"; 

    return 0; 
} 

답변

3

참조로

void comment(string& str) 
^^^^     ^^^ 

당신의 문자열을 전달 또는 함수에서 반환 값을받을 수 있습니다.

getline(cin, str); 
str = comment(str); 
^^^ 

그렇지 않으면이 함수는 문자열의 사본를받습니다. comment 함수 내부에있는 동안 str을 수정하면 main에 표시되지 않습니다.

+0

감사합니다. 이제 작동합니다 .. – Tuffy

+0

@BrownieTuffy 방금 참고로 전달하면 아무 것도 반환하지 않아도됩니다. – stardust

+0

그래 .. 고마워 .. – Tuffy

관련 문제