对字符串数组进行一次性排序
sorting array of strings one off
这段代码应该制作一个字符串数组,随机排序,然后打印顺序。不幸的是,它在其中一个空格中添加了一个空行(我认为这是getline的做法)。有什么办法解决的吗?我尝试将数组[0]设置为NULL;它抱怨运营商。。。
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <string>
#include <cstdlib>
using std::cout;
using std::endl;
using namespace std;
void swap (string &one, string &two)
{
string tmp = one;
one = two;
two = tmp;
}
int rand_loc (int size)
{
return (rand() % size);
}
int main()
{
srand(time(NULL));
int size;
cin >> size;
string *array = new string[size];
//array[0] = NULL ;
for (int x = 0; x < size; x++)
{
getline(cin, array[x]);
}
//for (int x = 0; x < size; x++)
//{
// swap (array[rand_loc(size)], array[rand_loc(size)]);
//}
cout << endl;
for (int x = 0; x < size; x++)
{
//out << array[x] << endl;
int y = x + 1;
cout<<y<<"."<<" "<<array[x]<<endl;
}
delete[] array;
}
对getline()
的第一次调用将立即命中用户在输入size
后输入的换行符,因此将返回一个空字符串。尝试在第一次调用getline()
之前调用cin.ignore(255, 'n');
。这将跳过最多255个字符(任意选择的数字),直到遇到n
为止(换行符也将被跳过)。
编辑:正如@Johnyweb和@ildjarn所指出的,std::numeric_limits<streamsize>::max()
是比255
更好的选择。
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中实现一个简单的一次性冒泡排序
- 对字符串数组进行一次性排序