没有输入数字时,如何删除"Sorted:[space]"后的空格?
How can I remove the space after "Sorted:[space]" when there are no input number?
我正试图编写一段代码来对整数向量进行排序。我的代码已经完成,并且可以工作。当没有输入数字时,如何删除"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: ";
如果没有输入数字,那么向量将为空。因此,您可以使用基于此的条件来打印额外的空间或不打印。
相关文章:
- 从 MSVC14 切换到 MSVC16 会导致"compiler is out of heap space (C1060)"错误
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- boost :: filesystem :: space()报告错误的磁盘空间
- 模块名称是否驻留在单独的"name space"中,或者它们可能与例如变量名称发生冲突?
- 将Space分离的值文本转换为使用C 的.CSV,然后保存
- 调试"Invalid address space"错误
- 如何使用 c++ 从 stdin int 读取 跳过","和"Space"直到"n"
- SDL 2 Space keydown未检测到,但Space keyup工作正常
- 对未定义的C++班次操作员行为和换行"pattern space"感到困惑
- 如何将"Alt+space"热键绑定到Qt中的插槽?
- 在字符串中查找'space'字符时出错
- 为什么Java在"Remove Duplicates from Sorted List"中比c++运行得更快?
- 如何删除 Ucrustify "tab tab SPACE"中的空格 - 缩进?
- 字符串类型从用户获取输入'space'
- RapidXML 是否支持 xml:space= "preserve" ?
- C++ 'Using space as a delimiter'
- white space and makefile
- 如何在类声明范围内使用“using space::function”
- 没有输入数字时,如何删除"Sorted:[space]"后的空格?