-
C++ (
http://www.daniweb.com/forums/forum8.html)
| Starz20 | Apr 9th, 2005 7:18 pm | |
| Strings and For Loops Hello everyone. My instructor has asked me to write a program that accepts a string as input from a user and prints the string in reverse. I have to use a "for" loop to reverse the string. I am also suppose to allow the user to input more than one string. I think I have done a pretty job at all of the above except for allowing the user to input an additional string. I am taking an intro to C++ and am very new to C++. In the program I have done so far I have defined a character limit of 256. I am confused on how to alow the user to input an additional string. I am not really for sure where to justify this in the body of the program or if it has to be done in the beginning. Any help would be greatly appreciated.
I was thinking it would be here, but I changed the value it did not work.
for (i=0; i<length; i++)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 256
int main(void)
{
char str[MAXLINE], rev[MAXLINE];
int i, length;
/*--------------------------------------------
* Read string and determine length
*--------------------------------------------*/
printf("Enter string: ");
scanf ("%s", str);
length= strlen(str);
/*---------------------------------------------
* Build the reversed string and print it.
* Don't forget to add the terminating 0!
*---------------------------------------------*/
/* loop 2 times */ this did not help
for (i=0; i<length; i++)
rev[length-i-1] = str[i];
rev[length] = 0;
printf("reverse string: %s\n\n", rev);
/*---------------------------
* Palindrome?
*---------------------------*/
if (strcmp (str,rev) == 0)
printf ("Palindrome!\n\n");
else
printf ("Not a Palindrome\n\n");
return 0;
} Code tags added. -Narue |
| Narue | Apr 9th, 2005 7:28 pm | |
| Re: Strings and For Loops Throw the whole thing in a loop and break from the loop if the user enters something that isn't valid:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 256
int main(void)
{
char str[MAXLINE], rev[MAXLINE];
int i, length;
for ( ; ; ) {
/*--------------------------------------------
* Read string and determine length
*--------------------------------------------*/
printf("Enter string or EOF to quit: ");
if ( scanf ("%s", str) != 1 )
break;
length = strlen(str);
/*---------------------------------------------
* Build the reversed string and print it.
* Don't forget to add the terminating 0!
*---------------------------------------------*/
for (i=0; i<length; i++)
rev[length-i-1] = str[i];
rev[length] = 0;
printf("reverse string: %s\n\n", rev);
/*---------------------------
* Palindrome?
*---------------------------*/
if (strcmp (str,rev) == 0)
printf ("Palindrome!\n\n");
else
printf ("Not a Palindrome\n\n");
}
return 0;
} |
| All times are GMT -4. The time now is 10:49 am. | |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC