简体   繁体   中英

std::cout is not printing

When I print out using std::cout , it doesn't print anything to the terminal:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

std::string multiplystr(std::string string, int mult) {
    for (int i = 1; i < mult; i++)     {
        string = string + string;
    }
    return string;
}

class entry {
public:

    entry(int width) {
        int frameWidth = width;
    }

    int frameWidth;
    std::string framechar = "-";

    std::string frame = multiplystr(framechar, (frameWidth + 4));
    std::string justout = frame + '\n';
};

int main() {
    entry x1(15);
    std::string out1 = x1.frame;
    std::cout.flush();
    cout << "out1" << std::endl;
}

However, if I delete everything except the print statement, it prints properly. Do you know why it does this?

I also used std::flush and it does not work.

Your code has undefined behavior , so literally anything could happen 1 .

In your entry class, the constructor body is assigning its input width value to a local variable named frameWidth which shadows the class member of the same name. As such, the frameWidth member is never initialized.

You are then passing the frameWidth member to the mult parameter of multiplystr() when initializing the frame member. The frame member is initialized before the constructor body begins running, so even if you fixed the constructor body to get rid of the local variable and assign the width value to the frameWidth member correctly, by then it is too late, the damage has already been done.

1 : In my test, when I run the code, I get a runtime error before the print statement is reached, because mult ends up being a very large value that causes the loop to blow up available memory.

To fix that, you need to initialize the frameWidth member in the constructor's initialization list instead of the constructor body. The initialization list will initialize frameWidth before the frame member is initialized, and thus before multiplystr() is called.

Try this:

#include <iostream>
#include <vector>
#include <string>

std::string multiplystr(std::string s, int mult) {
    for (int i = 1; i < mult; i++)     {
        s += s;
    }
    return s;
}

class entry {
public:

    entry(int width) : frameWidth(width) {}

    int frameWidth;
    std::string framechar = "-";

    std::string frame = multiplystr(framechar, (frameWidth + 4));
    std::string justout = frame + '\n';
};

int main() {
    entry x1(15);
    std::string out1 = x1.frame;
    std::cout << "out1 = " << out1 << std::endl;
}

Online Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM