如何排除"排序后的空格:[空格]"没有输入号码的时候?

时间:2016-08-05 23:24:06

标签: c++

我正在尝试编写一个代码来对整数向量进行排序。我的代码已经完成,并且可以正常运行。如何排除"排序后的空格:[空格]"没有输入号码的时候?这是我的代码:

#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;
}

任何帮助表示赞赏!谢谢!

2 个答案:

答案 0 :(得分:1)

将行cout << "Sorted: ";替换为以下

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

答案 1 :(得分:0)

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