gpt4 book ai didi

c++ - 交换字符串数组中的字符串

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

不确定我做的对不对。但我试图显示输出 cat the sideways ran 而不是 the cat ransideways

#include <string>
#include <iostream>
using namespace std;

void doSwap(string string1, string string2);

int main() {
string theArray[5] = {"the", "cat", "ran", "sideways"};
int i;
for (i = 0; i < 4; i++) {
doSwap(theArray[i], theArray[i+1]);
cout << theArray[i] << " ";
}
}

void doSwap (string string1, string string2) {
string temp;
temp = string1;
string1 = string2;
string2 = temp;
}

不确定我做的是否正确。

最佳答案

您应该通过引用传递字符串,因为您正在改变它们。编写代码的方式是发送要交换的字符串的临时拷贝,实际上是交换拷贝,而不是在数组中交换它们。更新代码:

#include <string>
#include <iostream>
using namespace std;

void doSwap(string string1, string string2);

int main() {
string theArray[] = {"the", "cat", "ran", "sideways"};
int i;
for (i = 0; i < (sizeof theArray)/sizeof(string); i++) {
doSwap(theArray[i], theArray[i+1]);
cout << theArray[i] << " ";
}
}

void doSwap (string &string1, string &string2) {
string temp;
temp = string1;
string1 = string2;
string2 = temp;
}

关于c++ - 交换字符串数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36749398/

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