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?
// asdf.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
usingnamespace 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 = newchar[counter];
And when you are done with the string stored in that palindrome variable, make sure you delete it to save resources:
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)