Output and Input at Same Line using IOSTREAM

微笑、不失礼 提交于 2019-12-11 08:04:52

问题


I want to use the iostream input and output operators in the same statement, not to be nicer to the user but the look I was trying not successfully obtained.

Code fragment:

int value = 0;
std::cout << "Number 1: " << std::cin >> value << std::endl;

Is there any way to do this using only cin cout?


回答1:


struct IO {
    template <typename T>
    const IO & operator << (const T & t) const {
        std :: cout << t;
        return *this;
    }

    template <typename T>
    const IO & operator >> (T & t) const {
        std :: cin >> t;
        return *this;
    }
};

IO () << "Number 1: " >> value;



回答2:


a bit messy but I think this is what you wanted

std::cout<<"Data : "<<val<<std::endl<<(std::cin>>val)<<"\r"<<"\t\r\n"<<std::flush;



回答3:


std::cout << "Number 1: ";
std::cin >> value;

Should do the trick.



来源:https://stackoverflow.com/questions/6597654/output-and-input-at-same-line-using-iostream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!