C++ 你如何让数字在右边排成一行?
似乎setw()将数字排列在左边,如:C++ 你如何让数字在右边排成一行?,c++,C++,似乎setw()将数字排列在左边,如: a $32 b $34.3 c $22.93 但是你怎么能做这样的事情: a $32 b $34.3 c $22.93 std::cout << std::right << std::setw(10) << x << std::endl; #include <iostream> #include <iomanip> #include &
a $32
b $34.3
c $22.93
但是你怎么能做这样的事情:
a $32
b $34.3
c $22.93
std::cout << std::right << std::setw(10) << x << std::endl;
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
char someChar = 'a';
double cost = 0;
stringstream ss;
ss << "$" << cost;
std::cout << someChar << std::right << std::setw(10) << ss.str() << std::endl;
// This line to clear the stringstream
ss.str("");
像这样使用“std::right”:
a $32
b $34.3
c $22.93
std::cout << std::right << std::setw(10) << x << std::endl;
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
char someChar = 'a';
double cost = 0;
stringstream ss;
ss << "$" << cost;
std::cout << someChar << std::right << std::setw(10) << ss.str() << std::endl;
// This line to clear the stringstream
ss.str("");
std::cout像这样使用“std::right”:
a $32
b $34.3
c $22.93
std::cout << std::right << std::setw(10) << x << std::endl;
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
char someChar = 'a';
double cost = 0;
stringstream ss;
ss << "$" << cost;
std::cout << someChar << std::right << std::setw(10) << ss.str() << std::endl;
// This line to clear the stringstream
ss.str("");
std::cout还值得注意的是,setprecision()
的存在是为了防止您想在小数点上排列。您如何将一个美元符号合并到您上面编写的代码中,以便它看起来像是我希望在OP中输出的第二个东西?如果我尝试cout@user3064097之类的方法,您可以解决“$”问题通过使用stringstream,我将更新答案以支持该问题。@user3064097使用“用右键修复”问题,我目前不知道为什么,但如果使用cout,它工作正常。setprecision()
存在,以防您想按十进制排列。您如何将美元符号合并到您上面编写的代码中,使其看起来像我希望在OP中输出的第二个东西?如果我尝试cout@user3064097之类的方法,您可以使用stringstream解决“$”问题,我将更新答案以支持它。@user3064097因为使用了“用正确的方式修复”问题,我目前不知道为什么,但如果使用cout,它可以正常工作