对字符串数组进行一次性排序

sorting array of strings one off

本文关键字:一次性 排序 字符串 数组      更新时间:2023-10-16

这段代码应该制作一个字符串数组,随机排序,然后打印顺序。不幸的是,它在其中一个空格中添加了一个空行(我认为这是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更好的选择。