打印以在c++中的行上的特定位置输出

print to output at specific location on line in c++

本文关键字:定位 位置 输出 c++ 打印      更新时间:2023-10-16

打印出页眉后,我正试图打印到一行中的统一位置。这里有一个例子:

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::leftstd::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