gpt4 book ai didi

c++ - "Sorted:[space]"后面没有输入号码,如何去掉空格?

转载 作者:行者123 更新时间:2023-11-28 05:33:50 26 4
gpt4 key购买 nike

我正在尝试编写代码来对整数 vector 进行排序。我的代码已完成,并且可以正常工作。没有输入数字时,如何删除“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: ";

关于c++ - "Sorted:[space]"后面没有输入号码,如何去掉空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38799025/

26 4 0
文章推荐: javascript - 在 Electron 中动态添加选项元素到