1

我已经实现了两个数字的交换功能,这很好用。但是,我现在正在尝试交换两个字符串,但我以相同的顺序接收名称。有人知道我哪里出错了,或者我能做些什么来让名字改变位置吗?这是以下代码的示例:

#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;
}
4

4 回答 4

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);
}
于 2013-10-21T04:05:34.257 回答
0

在您的代码中, person1 和 person2 被定义为 2 个 char 数组而不是 char 指针变量,您不能交换它们,如果您将 2 个数组传递给以 2 个指针作为参数的 swapname 函数,它甚至不应该编译。

于 2014-07-15T11:12:52.067 回答
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;    
}
于 2013-10-19T23:13:55.010 回答
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 );
}
于 2013-10-19T22:55:16.940 回答