2

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;
}
1
  • 1
    You don't need to write your own swap(), there's a swap() in STL. Commented May 28, 2011 at 9:49

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Less arbitrary: std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+1 for decreased arbitrariness, but -epsilon for increased verbosity ;-)
It's not decreased arbitrariness, it's zero arbitrariness. I.e., it's correct.
@ildjarn: Granted; I was being too lazy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.