如何解决大家好,我正在解决一个简单的 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]);
,
首先,您只是交换字符串的第一个字符。 a[0]
是 a
的第一个字符,对于 b
也是如此。
其次,您要交换两次:一次使用 std::swap
,一次使用三个赋值和一个临时赋值。交换两次即可恢复原状!
交换一次
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]);
,
代码的几个问题 -
- 您需要将临时声明为字符
string a,b; // function to swap s and d (splendid day to dplendid say)
char temporary;
- 临时分配 b[0] 处的值
temporary = b[0]; //assign temp variable to b[0]
- 为 a[0] 分配临时值
a[0]= temporary;
这足以交换一次。最后的交换函数将撤消这些更改,因此要么删除它,要么不要手动交换字符。
这最终解决了我的问题,我得到了 dplendid 作为输出。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。