Carl Lindman
Carl Lindman

Reputation: 23

How to read cin into a dynamic array?

I'm trying to store a string entered by the user into a dynamic array. For "normal" arrays, you simply use the get function as I've used it here and everything works fine. However it seems that this doesn't work for dynamic arrays. When compiled, the program basically just skips the whole input segment and moves on to what comes after it. It doesn't even pause to let me type anything. So how do I store cin input into a dynamic array? Note: This is for a specific assignment, so please don't tell me to use a string or a non-dynamic array; I can't.

int arraySize;
cout << "Enter a maximum length for the string: ";
cin >> arraySize;
arraySize += 1;

char *inputPtr;
inputPtr = new char[arraySize];

cout << "Enter a string to be converted: ";
cin.get(inputPtr, arraySize);

Upvotes: 2

Views: 13455

Answers (2)

Loki Astari
Loki Astari

Reputation: 264421

When interacting with a human it is best to do so a line at a time.
The std::cin is line buffered so people type the answer followed by return. Thus you should adapt the same behavior in your code.

std::string   arraySizeString;
std::getline(std::cin, arraySizeString);  // Get user input.

// Convert input to type we want.
int           arraySize;
std::stringstream arraySizeStream(arraySizeString)
if (! (arraySizeStream >> arraySize))
{
    // Error user did not enter a number.
    // You may want to check if the user entered more than just a number
    throw 1;
}

// Now read the lines into a dynamically size array (or vector).
std::vector<std::string>  data(arraySize);
for(int loop = 0; loop < arraySize; ++loop)
{
    std::getline(std::cin, data[loop]);
}        

The problem you are having is that operator>> when used on a string only reads a "white space" seporated word from the input (it leaves the '\n' on the input stream). So if you combine operator>> with other read operations you need to remember to take this fact into consideration and compensate.

Upvotes: 3

SRF
SRF

Reputation: 979

This is not a problem of dynamic array. When you enter the size of array, the new line character is stored into a buffer. When it comes to the last line (cin.get), it is taken that new line character and exit the program. Try

cin >> inputPtr;

instead of

cin.get(inputPtr, arraySize);

Upvotes: 1

Related Questions