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

标签 c++ string random

这段代码应该创建一个字符串数组,对它们进行随机排序,然后打印顺序。不幸的是,它在其中一个空格中添加了一个空行(我认为这是 getline 所做的)。有什么想法如何解决这个问题吗?我尝试设置 array [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 后会立即命中用户输入的换行符,因此将返回一个空字符串。尝试调用cin.ignore(255, '\n');在第一次调用 getline() 之前。这将跳过最多 255 个(任意选择的数字)字符,直到 \n遇到(并且换行符也将被跳过)。

编辑:正如@Johnsyweb 和@ildjarn 指出的那样,std::numeric_limits<streamsize>::max()是一个比 255 更好的选择.

关于c++ - 一次性对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6159275/

相关文章:

java - 如何抛硬币并显示反面和正面计数?

c++ - 为类编写双向迭代器

来自带有未转义引号的动态数据的 JavaScript 字符串声明

c++ - 'a' 和 "a"有什么区别?

c#: 字符串格式

c - 该函数会返回均匀分布的随机值吗?

c++ - 函数在 h 文件上内联发布版本,并在 cpp 上实现调试版本

c++ - 从二进制文件中读取6字节8位整数

c++ - 当其中一个为负时,如何将两个 16 位值合并为一个 32 位值?

c - 随机生成的二维噪声