Help with printing array

I want to create a program that takes each letter from a sentence that a user types and stores it into an array and print it. I used pointer to define the size of the array. However, when I try to print the array, the program prints numbers(most likely the memory location) instead of the characters in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
	int* a; 
	string user_input; 
	cout << "Please type your sentence\n";
	getline(cin, user_input);

	int lengOfStr = user_input.length();

	a = new int[lengOfStr];

	for (int i = 0; i < lengOfStr; i++)
	{
		a[i] = user_input[n];
		cout << a[i];   // THIS line is the issue
	}

	_getch();
	return 0;
}
Take a look at line 7:
int* a = nullptr; // It should be a char not int

Line 14:
a = new int[lengOfStr]; // Dynamically allocate the char not int

Line 18:
a[i] = user_input[n]; // The variable n is not declared or initiated, maybe is supposed to be i.

Before you return 0, since you are dynamically allocating by using new, you should use delete as well.

1
2
delete a;
a = nullptr;


I hope it helps.
Last edited on
It worked perfectly now! Thank you so much.
Topic archived. No new replies allowed.