gpt4 book ai didi

c++ - 如何从字符串执行 std::left

转载 作者:行者123 更新时间:2023-11-30 01:56:14 29 4
gpt4 key购买 nike

我正在尝试使用一个函数 myCout在其参数中有一个字符串。该字符串旨在设置输出的对齐方式。那就是如果我们有 "left"作为论点 cout<<std::left;应该被执行。

我在下面附上了我的代码。

ostream & myAlign (string str) {

if (str == "left")
return std ::left ;
else
return std::right ;
}

template <class T>
void myCout (int width, char fill, T var, string a) {

cout << setw(width) << setfill(fill) << setprecision(2) << myAlign(a) << std:: fixed << var << "\t" <<flush ;
return ;
}

提前感谢您的帮助

最佳答案

IO 操纵器并不神奇,但想想它们可能会很奇怪。有几种方法可以做到这一点,这只是其中一种,模仿您正在寻找的行为..

#include <iostream>
#include <iomanip>

class myAlign
{
public:
explicit myAlign(const std::string& s)
: fmt((s == "left") ? std::ios::left : std::ios::right)
{}

private:
std::ios::fmtflags fmt;

friend std::ostream& operator <<(std::ostream& os, const myAlign& arg)
{
os.setf(arg.fmt);
return os;
}
};

int main(int argc, char *argv[])
{
std::cout << myAlign("left") << std::setw(10) << "12345" << std::endl;
std::cout << myAlign("right") << std::setw(10) << "67890" << std::endl;
return 0;
}

输出

12345     
67890

注意:一个类似但复杂得多的相关问题 can be found here .

关于c++ - 如何从字符串执行 std::left,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19972041/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com