-
Arrays
Hi,
I would like to know were my error(s) are in this program. Could somebody look and help me out? I'm trying to get a string and reverse the order using for loops.
Code:
#include <iostream.h>
#include<string.h>
//void ReverseIt(char [], char []);
int main()
{
char str[50], copy[50];
int i,j,length;
length = strlen(str);
cout<<"\nEnter a string: "<<endl;
cin.getline(str,49);
cout<<"\nYou entered " << str <<" !" << endl;
for(i=0;i<50;i++)
{
cout<<"\nYou entered " << str[i] << endl;
for(j=0;j>50;j--)
{
cout<<"\nThe reverse is " << copy[j] <<endl;
}
}
return 0;
}
-
I'll point out just one error..
for(i=0;i<50;i++)
i should go up to length, not 50. If the string is less than 50 characters, you are going to go into uninitlized memory.
-
Like wise, this is wrong:
for(j=0;j>50;j--)
Its going from 0 and down, until its greater than 50? Hmm, I think that will take some doing... (Should start at length and down to 0.)
Also, the second for loop should _not_ be inside the first one. Why display the reversed string after every character of the initial string?
-
<Also, the second for loop should _not_ be inside the first one. Why display the reversed string after every character of the initial string?> I didn't mean for that to happen...I just don't know what I'm doing and I'm trying to learn. I'm trying to take the string that is entered and display it as well as display the same string backwards.
-
change Code:
length = strlen(str); /* here you get the lenth before its entered by the user resulting in an incorrect lenth */
cout<<"\nEnter a string: "<<endl;
cin.getline(str,49);
to Code:
cout<<"\nEnter a string: "<<endl;
cin.getline(str,49);
length = strlen(str); /* here you get the actual length of the string the user has entered */
-
...and here's your fixed loop(s) Code:
for(i=0;i<length;i++)
{
cout<<"\nYou entered " << str[i] << endl;
}
for(j=length;j>length;j--)
{
cout<<"\nThe reverse is " << copy[j] <<endl;
}
-
You also try to print "copy" without assigning the values of "str" to it. And use better spacing. This looks bad:
for(i=0;i<len;i++)
Try instead:
for(i = 0; i < len; i++)
or even:
for( i = 0; i < len; i++ )
Code:
#define MAX 50 /*..now we just change this instead of editing program later ;) */
int main() {
char str[MAX], copy[MAX];
int i, j, length;
do{
cout<<"\nEnter a string, type 'q' and ENTER to quit: "<<endl;
cin.getline(str, MAX);
length = strlen(str);
cout << "\nYou entered: " << endl;
for(i = 0; i < length; i++)
{
cout << str[i] << endl;
}
cout << "\nThe reverse is " <<endl;
for(j = length-1; j >= 0; j--)
{
cout << str[j] <<endl;
}
}while(str[0] != 'q');
return 0;
}
-
nah, I liked my version better :D