我是C++ STL库的新手,需要帮助。
我想添加两个数字,假设A= 4555和B= 50,并将它们输出为:
四五五五
+50
4605
另一个例子:
500000 + 12
500000
.=‘3’>再加12
500012
如果我将A和B同时存储在整数数据类型中,而符号'+‘存储在字符数据类型中。如何操作它们以获得首选输出。我只是想不出如何将两个变量组合在一起。
发布于 2015-04-13 17:03:23
如果您可以在来自std::setw的<iomanip>中使用常量宽度(或等于所涉及数字的最大宽度的可变宽度)为:
#include <iostream>
#include <iomanip>
#include <string>
void display_sum(int a, int b)
{
std::cout << std::setw(10) << a << "\n"
<< std::setw(10) << ("+" + std::to_string(b)) << "\n"
<< std::setw(10) << (a+b) <<"\n" << std::endl;
}
int main()
{
display_sum(4555, 50);
display_sum(500000, 12);
display_sum(503930, 3922);
}输出:
4555
+50
4605
500000
+12
500012
503930
+3922
507852在线演示
发布于 2015-04-13 17:19:56
您可以使用操纵者std::showpos、std::noshowpos和std::setw:
#include <iostream>
#include <iomanip>
int main() {
int a = 4555;
int b = 50;
std::cout
<< std::noshowpos << std::setw(10) << a << '\n'
<< std::showpos << std::setw(10) << b << '\n'
<< std::noshowpos << std::setw(10) << (a+b) << '\n';
}如果您想要一个取决于值的宽度,您可以使用三个std::strings流(S)并创建中间字符串(没有setw)。之后,使用setw的每个字符串的最大长度打印字符串:
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
int main() {
int a = 4555;
int b = 50;
std::ostringstream as;
std::ostringstream bs;
std::ostringstream rs;
as << std::noshowpos << a;
bs << std::showpos << b;
rs << std::noshowpos << (a+b);
unsigned width = std::max({ as.str().size(), bs.str().size(), rs.str().size() });
std::cout
<< std::setw(width) << as.str() << '\n'
<< std::setw(width) << bs.str() << '\n'
<< std::setw(width) << rs.str() << '\n';
}另请参阅:
注意:您可以看看std::internal的机械手。
发布于 2016-04-30 20:48:11
在您的示例中,字段最多可以容纳7个字符。也许您想在编写之前将字符串调整为7。例如fname.resize(7)。
要将其格式化为您想要的格式,您需要使用#include <iomanip>并使用std::left和std::setw(7)。
file1 << left << setw(7) << fname
<< tab << setw(7) << lname
<< tab << setw(7) << street
<< tab << setw(7) << city
<< tab << setw(7) << state
<< tab << setw(7) << zip << endl;https://stackoverflow.com/questions/29610734
复制相似问题