简体   繁体   中英

Strange behaviour of std::cout after function call

I have a simple program that set unsigned int variable. Well, I have one problem. std::cout works fine until InputCLI is called.

First time program prints line when debugger reaches line that contain std::cout

 std::cout << "debugNumber" << debugNumber; 

After InputCLI call program prints lines only with \\n untill it reaches std::cin operator. Whats wrong?

I'm coding in Eclipse (Linux). The moment before std::cin >> wait; was executed:

在此输入图像描述

#include <iostream>
#include <limits>

unsigned int InputCLI(unsigned int& x);
int main() {
    int wait;
    unsigned int debugNumber = 0;
    std::cout << "debugNumber " << debugNumber;
    std::cout << "Enter debug number\n";
    InputCLI(debugNumber);
    std::cout << "debugNumber\n";
    std::cout << "debugNumber " << debugNumber;
    if (debugNumber == 6) {
        std::cout << "bubu";
    }
    std::cin >> wait;
    return 0;
}

unsigned int InputCLI(unsigned int& x) {
    if (std::cin >> x, std::cin.fail()) {
        if (std::cin.bad() || std::cin.eof())
            return -1;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits < std::streamsize > ::max(), '\n');
        return -2;
    }
    return 0;
}

If I dont add \\n or std::endl std::cout will buffer data?

Yes, exactly.

std::flush explicitly flushes the stream. '\\n' on its own doesn't do any flushing at the C++ level, but may trigger a flush at a lower level. std::endl prints a '\\n' then does a std::flush .

Certainly, without any of those, you can't realistically expect a flush before your std::cin .

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