字符串C ++中的字符交换

时间:2011-12-13 18:29:03

标签: c++ replace swap ifstream

我不知道为什么这不起作用,我需要交换两个字符作为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;
}               

4 个答案:

答案 0 :(得分:7)

ifelse if中,您需要使用==代替=。在C ++ / C中,您使用==进行比较,使用=进行分配。

答案 1 :(得分:7)

if( c == a )
{
    outFile<< b;
}
else if (c == b)
{
    outFile<< a;
}

=用于分配,使用==进行比较。

你拥有它的方式,只要a不是0(整数0,而不是字符'0'),第一个分支将始终执行。

答案 2 :(得分:7)

if( c = a )else if (c = b)是可疑的。您分别将a的值和b的值分配给c。我相信如果赋值操作成功完成(也就是它),则块将执行。我相信您需要==运算符,而不是=运算符。

答案 3 :(得分:6)

您正在分配值而不是测试。

应该是

if (c == b)

if (c == a)

相关问题