declare array without specified size

Feb 20, 2009 at 1:22am
#include <iostream>
#include <conio>


int main()
{

const int SIZE = 100;
char sentence[SIZE];

cout <<"Enter a sentence :"<<endl;
cin.getline(sentence,SIZE);
cout <<sentence;


getch();
return 0;
}

This is the simple coding that let us enter a sentence in a 100 element size of array variable.Is there anyway that let us enter the sentence without specified the size ?Hence we could enter the sentence without the limitation of 100,is it related to the pointer ?
Feb 20, 2009 at 3:13am
Technically, it's impossible to create an array of unknown size. In reality, it's possible to create an array, and resize it when necessary.

http://www.cplusplus.com/reference/stl/vector/
Feb 20, 2009 at 3:58am
Just use a string.
Feb 20, 2009 at 4:50am
To create an array with a size the user inputs - here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

int main()
{
	//Create a user input size
	int size;
	std::cout << "Enter Size Of Array : ";
	std::cin >> size;

	//Create the array with the size the user input
	int *myArray = new int[size];

	//Populate the array with whatever you like..
	for(int i = 0; i < size; ++i)
	{
		myArray[i] = rand() % 10;
	}

	//Display whats in the array...
	for(int i = 0; i < size; ++i)
	{
		std::cout << "Item In Element " << i << " of the array = : " << myArray[i] << std::endl;
	}

	//Delete the array
	delete[] myArray;

	return 0;
}


Manipulate something like this to possibly fit in how you want it.
Feb 20, 2009 at 5:28am
1
2
string sentence;
getline( cin, sentence );
Feb 20, 2009 at 5:32am
Dont forget to:
1
2
3
4
5
#include <string>

//and

using std::string;


EDIT: Sorry Bazzy mistake on my part - I hate using namespace std lol - sorry
Last edited on Feb 21, 2009 at 8:09pm
Feb 20, 2009 at 12:58pm
using namespace std; or using std::string;, not using namespace std::string; as std::string isn't a namespace
Feb 20, 2009 at 1:28pm
In C:
1
2
3
#include<stdlib.h>
int *myArray = (int *) malloc(size*2);
char *myChar = (char *) malloc(size);
Last edited on Feb 20, 2009 at 1:28pm
Topic archived. No new replies allowed.