arrays - 大家好,我正在处理 C++ 中的一个简单交换问题(两个字符串)。我无法让我的交换工作。我的输出只是“精彩的一天”
问题描述
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a, b, temporary; // function to swap s and d (splendid day to dplendid say)
cout << "Input two words: " << endl;
cin >> a >> b;
cin.get(); //capture user input // to add index parameters?
temporary = a[0]; //assign temp variable to a[0]
b[0] = a[0]; //allocate b to a
b[0] = temporary; //do swap
swap(a[0], b[0]);
cout << "The two words you entered are: " << a << " " << b << endl; //attempt output
return 0;
}
解决方案
如果要交换每个字符串的第一个字符,只需进行交换(不是交换和通过临时的手动操作):
swap(a[0], b[0]);