creating a palindrome program

I'm trying to master my knowledge of C++ by doing some random practice programs I find here and there. The one i'm trying to make right now is a program that asks the user for a string and checks if it's a palindrome.

I've come to a road block where a part of my code doesn't compile( the rest works as i meant them to work), could someone please explain why that line (marked with the comment //doesn't compile?) doesn't compile?


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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// asdf.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
	char palin[255];
	for(int k=0;k<255;k++)
	{
		palin[k] = 0;				//fills the palin string with '\0'
	}
	cout << "Enter the palindrome: " << endl;
	cin.getline(palin, 255); //gets the string puts it in
	
	
	int counter = 0;
	while(1)		//finds the position of the first '\0'
	{
		if(palin[counter] == '\0')
			break;
		
		counter++;
	}
	
	
	//takes all of the string except the spaces
	char palindrome[counter];                  //doesn't compile?
	for(int j=0;j<counter;j++)
	{
		if(palin[j]!=' ')
		palindrome[j]=palin[j];
	}

	cout << palindrome;			//testing if it copies right

	
	




	//pause and quit
	cout << "Press enter to continue..." << endl;
	cin.get();
	return 0;
}
You are trying to declare an array in a way that is allocated by the compiler. Because the value of "counter" is not available until the program runs, the compiler just won't compile.

Instead, do this:
 
char *palindrome = new char[counter];


And when you are done with the string stored in that palindrome variable, make sure you delete it to save resources:
 
delete[] palindrome;
BTW, there are functions out there that will give you the length of the string, instead of you having to look up for the null char yourself. Lookup strlen(), or the more secure strlen_s().
OK thanks for the array help, but if i used strlen() it would only find the length of the char array i declared right? If so, how could I create a char array with a dynamic length(other than the way i just did here)

(I finally found a use for pointers. I never thought i'd use them)
Last edited on
Come on, Google is making billions for a reason.

http://www.cplusplus.com/reference/clibrary/cstring/strlen/

strlen() will find the null char as you intend.

And pointers are fundamental. You will ALWAYS use pointers in any application that is worth anything.
Topic archived. No new replies allowed.