2017-10-18 3 views
-2

나는 홈페이지에 기능 (INT, 문자열)이 있습니다함수에서 문자열을 전달하는 방법은 무엇입니까?

string word("HELLO"); 
int x = 0; 
char choice; 
swap(x, word); 

나는 다음과 같은 함수에 전달하는, 아니 성공, 노력하고 있습니다 :

void swap(int, string) { 

int x = 0; 
string word = "HELLO"; 

cout << "Would you like to change a letter? Please enter the letter 
position. " << endl; 
cin >> x; 

if (x == 1) { 
    cout << "What do you want to change it to?" << endl; 
    cin >> word[0]; 

나는이 오류가 점점 계속 :

오류 C2664 '무효 표준 : 스왑 (표준 : exception_ptr &, 표준 : exception_ptr &) 던져()'에 'INT'에서 인수 1을 변환 할 수 없습니다 '표준 : exception_ptr &'

무엇을 제공합니까?

+3

는 swap''에서 함수의 이름을 변경하거나 – Tas

+1

귀하의 코드는 끔찍한 너무 지저분 해 보이는이 std' 네임 스페이스를 사용'명백한을 제거합니다. 함수 swap은 실제로 어떤 문자를 대체하는 것만 바꾸지 않습니다. 이름을 바꿉니다. 'std :: cin >> word [0];'뒤에 무엇을할까요? –

+0

다른 if/else 문입니다. 그래서 누군가가 1을 누르면 첫 글자가 바뀌는 아이디어입니다. 2가 두 번째를 변경합니다. –

답변

0

코드의 주요 문제점은 들여 쓰기입니다. 코드를 읽을 수없고 이해하기가 어렵습니다. 그것을 아름답게해라. 읽기 쉽고 구조화 된 코드를 작성하십시오. 들여 쓰기에 대한 자세한 내용은 다음 링크를 참조하십시오.

https://en.wikipedia.org/wiki/Indentation_style

다음으로 함수 선언이 있습니다. 정의하기 전에 함수를 선언하지 마십시오. 함수 선언은 main 함수의 맨 위에 있어야하고 함수의 정의는 main 함수 아래에 있어야합니다. 다음과 같은 링크에서 함수 선언에 대한 자세한 정보를 찾을 수 있습니다 : 당신이 string 인쇄하려면 char array를 사용하지 않기 때문에

http://en.cppreference.com/w/cpp/language/function

, 루프로 string을 통해 갈 쓸모가 없다. <string> 라이브러리를 포함하고 string 유형으로 작업하기 시작합니다. string 변수를 std::cout 안에 전달하면 string을 출력 할 수 있습니다.

마지막으로 main 함수 외부에서 string 변수를 조작하려고하므로 참조 매개 변수를 전달해야합니다. (void myFunction(std::string& parameter);. 이 방법으로, 메인 또는 다른 함수 내부에있는 원래 변수가 변경됩니다. 참조 (&)가 없으면 수정하려는 값이 변경되지 않습니다.

다음 링크는 참조 사용을 보여줍니다.

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

일부 변경 사항이 적용된 이유는 아래 내용을 읽어주십시오. change 기능을 교묘하게 변경했습니다. 이제 어떤 크기의 string 유형을 사용할 수 있습니다.

#include <iostream> 
#include <string> //When you are working on strings, use the string library. 

using namespace std; 

//Function declaration is very important. Have the declarations above main. 
void change(string&); 

int main() { 
    string word("HELLO"); 
    char choice; 

    cout << "The word is : " << endl; 

    cout << word << endl; 

    //No need for the for loop to print out the string as 
    // we are working on a string and not a char array. 
    // for (int i = 0; i < word.length(); i++) { 
    //  cout << word[i]; 
    // } 


    change(word); 

    cout << "The new word is" << endl << word << endl; 

    cout << "Would you like to enter another change ? Enter Y or N ? " << endl; 

    cin >> choice; 

    if (choice == 'y' || choice == 'Y') { 
     change(word); 
     cout << word << endl; 
    } 
    else { 
     cout << "Good Bye" << endl; 
    } 

    system("pause"); 

    return 0; 

} 


//When your datatype is to be modified outside the function, use the reference 
//parameter type '&'. 
//Without the reference type, your modified version of the type will only be modified 
//inside that function. 
//The original one will not be altered. 

void change(string& word) { 
    /* 
    * size_t is simply unsigned int, to work towards manipulation and accessing 
    * of string types, use unsigned int or std::size_t 
    */ 
    size_t x = 0; 

    cout << "Would you like to change a letter? Please enter the letter position. " << endl; 
    cin >> x; 

    //Check to see if the inputted value is within the string length range. 
    if(x > 0 && x <= word.length()) 
     cout << "What do you want to change it to?" << endl; 
    else{ 
     cout << "The entered position is outside the string size range\n"; 
     return; //Quit from the function if the condition is not met. 
    } 

    /* 
    * Instead of using if/else if statements, 
    * Just make a normal loop. Much simpler. 
    */ 

    for(size_t i = 0; i < word.length(); i++){ 
     if((x-1) == i) 
      cin >> word[i]; 
    } 
} 
+0

답변은 (대부분) 자체 포함되어야하며, 주석이 자격이 없다는 것을 언급하면 ​​통지없이 제거 될 수 있습니다. –

+0

@PasserBy 경고 해 주셔서 감사합니다! –

+0

이것은 좋은 일입니다. 다음 질문은 최적화였습니다. 원래 하드 카운터 대신에 길이()를 가졌지 만 오류가 발생했습니다. 내가 뭘 잘못했는지는 모르겠지만, size_t와 배열의 길이를 최선의 방법으로 활용하는 것을 이해합니다. –

관련 문제