2013-10-19 135 views
1

我已經實現了通過兩個數字交換功能,這很好。但是,我現在試圖交換兩個字符串,但我收到相同順序的名稱。有人會知道我錯了什麼地方,或者我可以做些什麼來讓名字改變位置?這裏是下面的代碼示例:C++:交換字符參考

#include "stdafx.h" 
#include <cstring> 
#include <iostream> 
#include <string> 

using namespace std; 

void swapages (int &age1, int &age2);   
void swapname(char *person1, char *person2); 

int _tmain(int argc, _TCHAR*argv[]) 
{ 
    char person1[] = "Alex"; 
    char person2[] = "Toby"; 
    int age1 = 22; 
    int age2 = 27; 


    cout << endl << "Person1 is called " << person1; 
    cout << " and is " << age1 << " years old." << endl; 
    cout << "Person2 is called " << person2; 
    cout << " and is " << age2 << " years old." << endl; 

    swapname(person1,person2); 
    swapages(age1,age2); 
    cout << endl << "Swap names..." << endl; 
    cout << endl << "Person1 is now called " << person1; 
    cout << " and is " << age1 << " years old." << endl; 
    cout << "Person2 is now called " << person2; 
    cout << " and is " << age2 << " years old." << endl; 

    system("pause"); 
    return 0; 
} 

void swapages(int &age1, int &age2) 
{ 
    int tmp = age2; 
    age2 = age1; 
    age1 = tmp; 
} 

void swapname(char *person1, char *person2) 
{ 
    char* temp = person2; 
    person2 = person1; 
    person1 = temp; 
} 
+1

好吧,正如你所說,「通過參考」。但我沒有看到任何參考。 –

+0

爲了能夠修改,您必須通過指針('char **',指向指針的指針)或引用('char *&')來傳遞'char *'指針,就像您對int中的int所做的那樣'swapages()')。順便說一句,[數組是邪惡的](http://www.parashift.com/c++-faq/arrays-are-evil.html),所以忘記它並使用['std :: string'](http:// en .cppreference.com/W/CPP /串/ basic_string的)。 – Drop

+1

如果你使用['std :: swap'](http://en.cppreference.com/w/cpp/algorithm/swap)和['std :: string'],你的代碼會更簡單(並且實際工作) (http://en.cppreference.com/w/cpp/string/basic_string)從標準庫。 – Blastfurnace

回答

0

的問題是,你想換是函數的局部變量,而你需要換字符串指針。所以你需要將一個字符串複製到另一個字符串中。此外,字符串可以有不同的長度,所以確切的交換將是不可能的。如果函數的參數是相同大小的數組(引用數組),那麼可以毫無問題地完成。例如,

void swap_name(char (&lhs)[5], char (&rhs)[5]) 
{ 
    char tmp[5]; 

    std::strcpy(tmp, lhs); 
    std::strcpy(lhs, rhs); 
    std::strcpy(rhs, tmp); 
} 
0

您需要稍作更改以使其按照您希望的方式工作。

void swapname(char **person1, char **person2); 
. 
. 
char *person1 = "Alex"; 
char *person2 = "Toby"; 
. 
. 
swapname(&person1, &person2); 
. 
. 

void swapname(char **person1, char **person2) 
{ 
    char* temp = *person2; 

    *person2 = *person1; 
    *person1 = temp;  
} 
+0

這是C代碼,而不是C++。你至少可以使用'char *&'參數。 –

1

您已經標記這是C++,並且已在包括<string>頭,那麼爲什麼不使用std:string,而不是所有的指針和數組?

void swapname(string &person1, string &person2) 
{ 
    string temp(person2); 
    person2 = person1; 
    person1 = temp; 
} 

int _tmain(int argc, _TCHAR*argv[]) 
{ 
    string person1 = "Alex"; 
    string person2 = "Toby"; 

    swapname(person1, person2); 
} 
0

在你的代碼,PERSON1和PERSON2被定義爲2個字符數組不是字符指針變量,你不能交換它們,如果你通過了2列到swapname函數,它接受兩個指針作爲參數,它應該甚至沒有編譯。