Search code examples
c++c++14ofstream

Can't write string on file C++


I'm trying to emulate a shift register of 32 bits. But I can't even write, neither the input or output on the file. It simply runs the file and closes. There is nothing written in there. Tried some solutions here, but nothing worked so far. The input is a string of 32 bits like this

"00000000000000000000000000000011".

The output should look like this

"00000000000000000000000000001100".

Shifting two bits to the left. I haven't finished the shift yet, I'm trying to understand why it doesn't show anything.

The weird thing about this is, I've created 32 bits multiplexes the same way and it works fine.

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();
}

Solution

  • std::vector<std::string> saida;
    

    This instantiates a new vector. Like all new vectors, it is completely empty, and contains no values.

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

    This assigns four values to saida[0] through saida[3]. Unfortunately, as we've just discovered, the saida vector is completely empty and contains nothing. This attempts to assign new values to nonexistent values in the vector, so this is undefined behavior, and pretty much a guaranteed crash.

    Additionally, no attempt is made to verify whether the entrada vector contains at least four values, this would be yet another reason for undefined behavior, and a crash.

    It is unclear what the intent of the shown code is, so it's not possible to offer any suggestion of possible ways to fix it. The description of the code does not match its contents. It is unclear what relationship exists between "32 bits" and a vector of strings, that may or may not have four values in it.

    The only thing that can be determined is that you get no output because your program crashes because of undefined behavior. Before you can assign a value to the ith element in the vector, the ith element must already exist. It doesn't, in the shown code. This results in undefined behavior and a crash.

    There are various ways of placing new values in a vector. A vector can be resize()d, or new values can be push_back()ed into a vector. It is unclear what should be done in this case, so for additional information and examples, see your C++ book so you can learn more about how either approach (and other approaches) work, so you can decide how you want to do what you are trying to do.