在此题中怎样交换两个整数和字符串
时间: 2024-03-12 19:50:23 浏览: 11
在程序中,可以使用一个临时变量来交换两个整数或字符串的值。下面是交换两个整数的示例代码:
```c++
int a = 5;
int b = 10;
int temp;
temp = a;
a = b;
b = temp;
// 现在a的值为10,b的值为5
```
上述代码中,我们定义了两个整数变量a和b,并声明了一个临时变量temp。然后,将变量a的值赋给temp,将变量b的值赋给a,最后将temp的值赋给b,这样就完成了a和b的值的交换。
下面是交换两个字符串的示例代码:
```c++
#include <string>
#include <iostream>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
string temp;
temp = str1;
str1 = str2;
str2 = temp;
cout << "str1: " << str1 << endl; // 输出:str1: world
cout << "str2: " << str2 << endl; // 输出:str2: hello
return 0;
}
```
上述代码中,我们定义了两个字符串变量str1和str2,并声明了一个临时变量temp。然后,将变量str1的值赋给temp,将变量str2的值赋给str1,最后将temp的值赋给str2,这样就完成了str1和str2的值的交换。注意,要使用string头文件中的string类型来定义字符串变量。