Dynamic character array

Attempting to dynamically allocate a name to a character array and getting very confused. Here is where I am at the moment:

Apologies for the awful code and any help much appreciated!

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
  #include "stdafx.h"
#include <iostream>

int main()
{
	using namespace std;
	char c = 0;
	int i = 0;
	int j = 1;
	char *str = new char[j];

	cout << "Please enter string: ";

	while (c != '\n')
	{
		cin >> c;
		str = new char[j];
		str[i] = c;
		i++;
		j++;
	}


	cout << "Entered string is:" << str << endl;
	delete[] str;

	return 0;
}
If you just want to read a string, there is a string class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "stdafx.h"
#include <iostream>
#include <string>

int main()
{
	using namespace std;

	cout << "Please enter string: ";	
	std::string str;
	cin >> str;

	cout << "Entered string is:" << str << endl;

	return 0;
}



If you know the string won't be longer than some value, you can create a char buffer that large.

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
#include "stdafx.h"
#include <iostream>

const size_t max_len = 256;

int main()
{
	using namespace std;

	cout << "Please enter string: ";	
	char str[max_len + 1];
	for (size_t i = 0; i != max_len; ++i)
	{
		cin >> str[i];
		if (str[i] == '\n')
		{
			str[i] = '\0';
			break;
		}
	}

	cout << "Entered string is:" << str << endl;

	return 0;
}



Or if you really want to dynamically allocate that string:

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
#include "stdafx.h"
#include <iostream>

const size_t max_len = 256;

int main()
{
	using namespace std;

	cout << "Please enter string: ";	
	char* str = new char[max_len + 1];
	for (size_t i = 0; i != max_len; ++i)
	{
		cin >> str[i];
		if (str[i] == '\n')
		{
			str[i] = '\0';
			break;
		}
	}

	cout << "Entered string is:" << str << endl;
	delete [] str;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.