declare array without specified size

#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 ?
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/
Just use a string.
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.
1
2
string sentence;
getline( cin, sentence );
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
using namespace std; or using std::string;, not using namespace std::string; as std::string isn't a namespace
In C:
1
2
3
#include<stdlib.h>
int *myArray = (int *) malloc(size*2);
char *myChar = (char *) malloc(size);
Last edited on
Topic archived. No new replies allowed.