没有输入数字时,如何删除"Sorted:[space]"后的空格?

How can I remove the space after "Sorted:[space]" when there are no input number?

本文关键字:Sorted space 空格 删除 数字 输入 何删除      更新时间:2023-10-16

我正试图编写一段代码来对整数向量进行排序。我的代码已经完成,并且可以工作。当没有输入数字时,如何删除"Sorted:[space]"后面的空格?这是我的代码:

#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
/* sort function */
void sort(vector<int>& v)
{
   for (int inc1 = 0; inc1 < v.size() - 1; ++inc1)
  {
    int minimum = inc1;
    for (int inc2 = inc1; inc2 < v.size(); ++inc2)
    {
        if (v[inc2] < v[minimum])
        {
            minimum = inc2;
        }
    }
    if (minimum != inc1)
    {
        int temporary = v[minimum];
        v[minimum] = v[inc1];
        v[inc1] = temporary;
    }
    if (v.empty())
    {
      return;
    }
  }
}
/* display function */
void display(vector<int> v)
{
  for (int inc1 = 0; inc1 < v.size(); ++inc1)
  {
    cout << v[inc1];
    if (inc1 != v.size() - 1)
    {
        cout << ", ";
    }
  }
cout << endl;
}
/* main function */
int main()
{
  /* getting inputs */
  cout << "Enter integers (one on each line, entering an empty line quits):" << endl;
vector<int> v;
string myString;
while (getline(cin, myString))
{
    /* if encounters a empty line, prints the output */
    if (myString.length() == 0)
    {
        break;
    }
    /* if not add values to the vector */
    else
    {
        v.push_back(atoi(myString.c_str()));
    }
}
cout << "Sorted: ";
/* function call to sort */
sort(v);
/* function call to display */
display(v);
getchar();
return 0;
}

感谢您的帮助!非常感谢。

用以下替换cout << "Sorted: ";

v.empty()? cout << "Sorted:": cout << "Sorted: ";

如果没有输入数字,那么向量将为空。因此,您可以使用基于此的条件来打印额外的空间或不打印。