消除24和124的空格

问题描述 投票:0回答:1
int main() {
  unsigned int low, high, i;

  do {
    cout << "Enter lower and upper values" << endl;

    cin >> low >> high;

    if (low > high) {
      cout << "Values must be in range 32 to 126 inclusive" << endl;
    } else if ((low < 32 || low > 126) || (high < 32 || high > 126)) {
      cout << "Values must be in range 32 to 126 inclusive" << endl;
    }
  } while (low > high || low < 32 || low > 126 || high < 32 || high > 126);

  cout << "Characters for ASCII values between " << low << " and " << high
       << endl;

  cout << "----+----+----+----+" << endl;

  for (i = low; i <= high; i++)
  {
    cout << (char)i;

    if ((i - low + 1) % 20 == 0)
    {
      cout << endl;
    }
  }

  cout << "\n----+----+----+----+" << endl;

  return 0;
}

输出几乎正确;但是空格不同。请参见下面的重点内容。特殊人物传说输入

65 124

您的输出

Enter lower and upper values
Characters for ASCII values between 65 and 124
----+----+----+----+
ABCDEFGHIJKLMNOPQRST
UVWXYZ[\]^_`abcdefgh
ijklmnopqrstuvwxyz{|

----+----+----+----+ // white space below ijklmnopqrstuv........

预期输出

Enter lower and upper values
Characters for ASCII values between 65 and 124
----+----+----+----+
ABCDEFGHIJKLMNOPQRST
UVWXYZ[\]^_`abcdefgh
ijklmnopqrstuvwxyz{|
----+----+----+----+

当下限为65而上限为124时,我无法弄清楚如何消除输出中的空白。该程序对于32和126以及其他值也是正确的,但是我不明白为什么我得到了末尾为65和124的空白。

c++ output
1个回答
0
投票

只需添加条件以检查是否为最后一个字符输出不要添加新行,像这样

for(i = low; i <= high; i++) {
  cout << (char)i;
  if((i - low + 1) % 20 == 0 && i != high) {
    cout << endl;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.