【问题标题】:Format C++ Output Columns, Limiting Each Field格式化 C++ 输出列,限制每个字段
【发布时间】:2013-03-24 21:31:56
【问题描述】:

我有一个任务,我需要输出一个包含歌曲信息的数组。我遇到的问题是格式化输出。我的作业指定了显示的每个字段的长度,但我找不到限制输出的好方法。例如,如果歌曲标题有 21 个字符,但必须为 18 个字符,我将如何防止它超过指定的 18 个字符。我正在使用 setw() 函数正确分隔所有内容,但它根本不限制输出。

【问题讨论】:

  • 尝试将字符串限制为 18 个字符?
  • 你使用的是 c++ 字符串吗?还是 const char*s?
  • 是的,我试图将其中一列限制为 18 列,其他列的大小不同,但如果我能找出一个列,我可以处理其余的列。我也在使用 C++ 字符串。
  • 那我想你可以在这里使用其中一个答案。

标签: c++ formatting setw


【解决方案1】:

您可以使用 string::resize 调整 c++ 字符串的大小。

// resizing string
#include <iostream>
#include <string>

int main ()
{
  std::string str ("I like to code in C");
  std::cout << str << '\n';

  unsigned sz = str.size();

  .resize (sz+2,'+');
  std::cout << str << '\n'; //I like to code in C++

  str.resize (14);
  std::cout << str << '\n';//I like to code
  return 0;
}

【讨论】:

    【解决方案2】:

    您可以从字符串中获取长度为 18 个字符的子字符串,然后将其输出。

    http://www.cplusplus.com/reference/string/string/substr/

    例子:

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main ()
    {
      string str="We think in generalities, but we live in details.";
      if(str.length()<=18) cout << str << endl;
      else cout << str.substr(0,15) << "..." << endl;
      return 0;
    }
    

    【讨论】:

      【解决方案3】:

      如果您不想修改原始字符串。

      string test("http://www.cplusplus.com/reference/string/string/substr/");
      string str2 = test.substr(0,18);
      cout<<str2 <<endl;
      

      如果您仍然不需要其余的测试。

      string test("http://www.cplusplus.com/reference/string/string/erase/");
      test.erase(18);  // Make sure you don't go out of bounds here.
      cout<<test<<endl;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-29
        • 2016-12-23
        • 2017-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多