无法在文件 C++ 上写入字符串

Can't write string on file C++

我正在尝试模拟 32 位的移位寄存器。但我什至不能写,无论是文件的输入还是输出。它只是运行文件并关闭。里面什么也没有写。在这里尝试了一些解决方案,但到目前为止没有任何效果。输入是这样一个32位的字符串

“00000000000000000000000000000011”。

输出应如下所示

“00000000000000000000000000001100”。

向左移动两位。我还没有完成轮班,我正在尝试了解为什么它没有显示任何内容。

奇怪的是,我用同样的方法创建了 32 位多路复用并且它工作正常。

void deslocador::shift(std::vector<std::string> entrada)
{
std::ofstream shifter("shift_left2.tv", std::ofstream::out);
std::vector<std::string> saida;

if(shifter.is_open())
{
    for(unsigned int i = 0; i < 3; i++)
    {
        saida[i] = entrada[i];
        saida[i].erase(saida[i].begin());
        saida[i].erase(saida[i].begin());
        saida[i] += "00";

        shifter << entrada[i] << "_" << saida[i] << std::endl;
    }

}else
    {
        std::cout << "Couldn't open file!";
    }

shifter.close();
}
std::vector<std::string> saida;

这将实例化一个新向量。与所有新向量一样,它完全是空的,不包含任何值。

for(unsigned int i = 0; i < 3; i++)
{
    saida[i] = entrada[i];

这会将四个值分配给 saida[0]saida[3]。不幸的是,正如我们刚刚发现的那样,saida 向量完全是空的,不包含任何内容。这试图将新值分配给向量中不存在的值,因此这是未定义的行为,并且几乎可以保证崩溃。

此外,没有尝试验证 entrada 向量是否包含至少四个值,这将是未定义行为和崩溃的另一个原因。

不清楚所显示代码的意图是什么,因此无法提供任何可能的修复方法建议。代码的描述与其内容不符。目前尚不清楚“32 位”与字符串向量之间存在什么关系,其中可能有也可能没有四个值。

唯一可以确定的是你没有得到任何输出,因为你的程序由于未定义的行为而崩溃。在为向量中的第 i 个元素赋值之前,第 i 个元素必须已经存在。它没有,在显示的代码中。这会导致未定义的行为和崩溃。

有多种方法可以将新值放入向量中。向量可以 resize()d,或者新值可以 push_back()ed 到向量中。不清楚在这种情况下应该做什么,因此有关更多信息和示例,请参阅您的 C++ 书籍,以便您可以了解更多关于这两种方法(和其他方法)如何工作的信息,这样您就可以决定您想要做什么正在努力。

这是我的工作!

void deslocador::shift(std::vector<std::string> entrada)
{
    std::ofstream shifter("shift_left2.tv", std::ofstream::out);
    std::vector<std::string> saida;
    saida.resize(entrada.size());

    if(shifter.is_open())
    {
        for(unsigned int i = 0; i < entrada.size(); i++)
        {
            saida[i] = entrada[i];
            saida[i].erase(saida[i].begin());
            saida[i].erase(saida[i].begin());
            saida[i] += "00";

            shifter << entrada[i] << "_" << saida[i] << std::endl;
        }

    }else
        {
            std::cout << "Couldn't open file!";
        }

    shifter.close();
}