gpt4 book ai didi

C++:通过 ref 交换字符

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:13 25 4
gpt4 key购买 nike

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

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

最佳答案

您已将其标记为 C++,并且包含了 <string> header 已经有了,为什么不使用 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);
}

关于C++:通过 ref 交换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19471938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com