Splitting Up Word/number for Palindrome

Hey everyone, I'm working on an assignment for determining if a string or number is a palindrome. My question is, how would you split a word/sentence or number up into individual parts? For example
cin >> value
(The user types in "puppy" or "112211")
Now the item in the stack is that word or number but I want it to be
P
U
P
P
Y

or
1
1
2
2
1
1

I'd rather not ask the user to input each character individually. Thanks.
If you get input as a string then you can access each element with [].
For example, with input PUPPY:
1
2
3
4
5
6
#include<string>
...
  std::string my_string;
  cin >> my_string;
  cout << my_string[0] << ' ' << my_string[3];
...
P P
Last edited on
Then could I just do a for loop through each stack and compare them? If they're equal then it's a palindrome and if they aren't then it obviously isn't.
pretty much you will read in the line entered by the user, you can use cin, but i'd use getline for strings.
Now a string in C++ is actually an array, so to access any of the letter you'd go about it in the same manner you'd access data from an array.

ex.
PUPPY
array[0] = P
array[1] = U
array[2] = P
array[3] = P
array[4] = Y

let me know if this doesn't make sense
That makes sense to me, but I'm just trying to figure out the syntax of how to set up usage of strings in the code, as I've never used them before. Also, I need the code to check both words and numbers, so would string work for a number also?
Hey I'm working on the project again and have a question. I used a string to push data into stack A, but now I'm trying to push stack A into stack B (so that it goes in inverse to stack A so I can then read through and check for a palindrome) but I'm not sure how to write that particular line. Here's the code thus far.

	int i = 0; //counter for characters
	char n = 0;
	stack_type a, b;

	a.clear_stack();
	b.clear_stack();
	cout << "Stacks have been cleared." << endl;
	cout << a.top << " is the top of stack A." << endl;
	cout << b.top << " is the top of stack B." << endl;
	
	cout << "Enter a word, sentence or number.  The program will see if it is palindromic." << endl;
	cout << "Enter your selection here =====> ";
	std::string s1;
	getline (cin,s1);
	cout << "The size of your input is " << s1.size() << " characters.\n" << endl;

	for (i=0; i < s1.size(); i++)
	{
		a.push(s1[i]);
	}

	while (!(a.empty_stack()))
	{
	a.pop(n);
	cout << n;
	}
	cout << " " << endl << endl;
}
Last edited on
Topic archived. No new replies allowed.