What is happening to my palindrome program? C++.
Here is what my code does. I have to strings. The user inputs into one of them. I use a for loop to enter the string into a second one in reverse. Then, I use strcmp to see if they are the same. If the output of strcmp is 0 the answer is trye, otherwise false. For some reason something is going really wrong with my copyString. I tried copying my for loop directly from a website to see if I was doing it wrong and i still get a weird value inside copString
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int main() {
char string1[20], copyString[20];
int i,x, length=0,j,flag=0;
cout << "Enter a string: ";
gets_s(string1);
length = strlen(string1) - 1;
for (i = length, j = 0; i >= 0; i--, j++)
{
copyString[j] = string1[i];
}
flag = (strcmp(string1, copyString));
cout << flag << endl << "here is 1: " <<string1 << endl << endl <<copyString;
if (flag == 0)
cout << "True";
else
cout << "False";
}
#include<iostream> #include<string.h> #include<string> using namespace std; int main() { char string1[20], copyString[20]; int i, x, length = 0, j, flag = 0; cout << "Enter a string: "; gets_s(string1); length = strlen(string1) - 1; for (i = length, j = 0; i >= 0; i--, j++) { copyString[j] = string1[i]; } copyString[j] = '\0'; // we have to end a string with '\0'. null-terminating character. flag = (strcmp(string1, copyString)); cout << flag << endl << "here is 1: " << string1 << endl << endl << copyString; if (flag == 0) cout << "True"; else cout << "False"; }
Get Answers For Free
Most questions answered within 1 hours.