打印以在c++中的行上的特定位置输出
print to output at specific location on line in c++
打印出页眉后,我正试图打印到一行中的统一位置。这里有一个例子:
PHRASE TYPE
"hello there" => greeting
"yo" => greeting
"where are you?" => question
"It's 3:00" => statement
"Wow!" => exclamation
假设它们中的每一个都存储在std::map<string, string>
中,其中key=phrase和value=type。我的问题是,简单地使用制表符取决于我在其中查看输出的控制台或文本编辑器。如果制表符宽度太小,我不确定它将被打印到哪里。我尝试过使用setw
,但它只打印离短语末尾固定距离的分隔符("=>"(。有简单的方法吗?
注意现在假设我们总是知道短语的长度不会超过16个字符。如果是的话,我们不需要考虑该怎么办。
使用std::left
和std::setw
:
std::cout << std::left; // This is "sticky", but setw is not.
std::cout << std::setw(16) << phrase << " => " << type << "n";
例如:
#include <iostream>
#include <string>
#include <iomanip>
#include <map>
int main()
{
std::map<std::string, std::string> m;
m["hello there"] = "greeting";
m["where are you?"] = "question";
std::cout << std::left;
for (std::map<std::string, std::string>::iterator i = m.begin();
i != m.end();
i++)
{
std::cout << std::setw(16)
<< std::string(""" + i->first + """)
<< " => "
<< i->second
<< "n";
}
return 0;
}
输出:
"你好"=>问候"你在哪里?"=>问题
请参阅http://ideone.com/JTv6na用于演示。
printf(""%s"%*c => %s",
it->first.c_str(),
std::max(0, 16 - it->first.size()),
' ',
it->second.c_str());`
与Peter的解决方案相同,但将填充放在引号之外。它使用带有长度参数的%c
来插入填充。
如果你不反对C风格的打印,printf
非常适合这类东西,而且可读性更强:
printf(""%16s" => %sn", it->first.c_str(), it->second.c_str());
在C++程序中使用printf和friends并没有错,只是要小心混合iostreams和stdio。您总是可以快速进入缓冲区,然后用iostreams输出。
您可能会发现这个函数很有用:
#include <iostream>
#include <iomanip>
void printRightPadded(std::ostream &stream,const std::string &s,size_t width)
{
std::ios::fmtflags old_flags = stream.setf(std::ios::left);
stream << std::setw(width) << s;
stream.flags(old_flags);
}
你可以这样使用它:
void
printKeyAndValue(
std::ostream &stream,
const std::string &key,
const std::string &value
)
{
printRightPadded(stream,""" + key + """,18);
stream << " => " << value << "n";
}
如果你不能使用setw,一个简单的替代方法是用空格修补所有短语,使它们都是16个字符长。
我个人认为C样式打印对于格式化打印来说更可读。使用printf
,您还可以使用*
格式化程序来处理列宽。
#include <cstdio>
int main() {
printf("%-*s%-*sn", 10, "Hello", 10, "World");
printf("%-*s%-*sn", 15, "Hello", 15, "World");
// in the above, '-' left aligns the field
// '*' denotes that the field width is a parameter specified later
// ensure that the width is specified before what it is used to print
}
输出
Hello World
Hello World
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 是与初始类同一内存位置的重新定位类
- 如何在使用网格布局时重叠qwidgets,并将重叠的widget定位在距离窗口边界特定距离的位置
- 我不知道如何定位最高随机数的位置
- 如何在MFC上设置窗口位置以将其定位到屏幕顶部
- 将QGraphicsSvgItem的中心定位在一个位置上。
- 如何定位WinRT异步方法调用中出现错误的位置
- 重定位表项在平面二进制文件中的存储位置