开发者

sorting array of strings one off

开发者 https://www.devze.com 2023-03-08 18:14 出处:网络
This code is supposed to make a array of strings, randomly order them, and then print the order. Unfortunately it adds a blank line in one of the spaces ( i think this is getline\'s doing). Any ideas

This code is supposed to make a array of strings, randomly order them, and then print the order. Unfortunately it adds a blank line in one of the spaces ( i think this is getline's doing). Any ideas how to fix that? I tried setting array [0] = NULL; it complains about operators...

#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;
}


The first call to getline() will immediately hit the newline that the user entered after inputting size, and will therefore return an empty string. Try to call cin.ignore(255, '\n'); before the first call to getline(). This will skip up to 255 (an arbitrarily selected number) characters until a \n is encountered (and the newline will be skipped as well).

Edit: As @Johnsyweb and @ildjarn point out, std::numeric_limits<streamsize>::max() is a much better choice than 255.

0

精彩评论

暂无评论...
验证码 换一张
取 消