文件 C++ 中的字符交换
我不知道为什么这不起作用,我需要交换作为 a 和 b 输入的两个字符,它可以编译,但所有字符都被替换为作为 b 输入的字符,有什么建议吗?
while (n != exist)
{
cout<<"What is the letter you want to swap?"<<endl;
cin>>a;
cout<<"What is the letter you want to swap it with?"<<endl;
cin>>b;
if (inFile.is_open())
{
while (inFile.good())
{
inFile.get(c);
if( c = a )
{
outFile<< b;
}
else if (c = b)
{
outFile<< a;
}
else
{
outFile<< c;
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
cout<<"Another letter? <n> to stop swapping"<<endl;
cin>>n;
}
I dont know why this will not work, i need to swap the two chars enterd as a and b, it compiles but all the chars are replaced with the char inputted as b, any advise?
while (n != exist)
{
cout<<"What is the letter you want to swap?"<<endl;
cin>>a;
cout<<"What is the letter you want to swap it with?"<<endl;
cin>>b;
if (inFile.is_open())
{
while (inFile.good())
{
inFile.get(c);
if( c = a )
{
outFile<< b;
}
else if (c = b)
{
outFile<< a;
}
else
{
outFile<< c;
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
cout<<"Another letter? <n> to stop swapping"<<endl;
cin>>n;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在
if
和else if
中,您需要使用==
而不是=
。在 C++/C 中,使用==
进行比较,使用=
进行赋值。In
if
andelse if
you need to use==
instead of=
. In C++/C you use==
for comparison and=
for assignment.=
用于赋值,==
用于比较。按照你的方式,只要 a 不为 0(整数 0,而不是字符“0”),第一个分支将始终被执行。
=
is for assignment, use==
for comparison.The way you have it, as long as a is not 0(the integer 0, not the character '0'), that first branch will always be executed.
if( c = a )
和else if (c = b)
是可疑的。您分别将 a 的值分配给 c,将 b 的值分配给 c。我相信如果赋值操作成功完成(就是这样),该块就会执行。我相信您需要==
运算符,而不是=
运算符。if( c = a )
andelse if (c = b)
are suspect. You are assigning the value of a to c and the value of b to c, respectively. I believe if the assignment operation completes successfully (which is it), the block will execute. I believe you want the==
operator, instead of the=
operator.您正在分配值而不是测试。
应该是
if (c == b)
和
if (c == a)
You are assigning values instead of testing.
It should be
if (c == b)
and
if (c == a)