Hello, I have a question regarding the following code. I have two functions in it, one called SetupReverse() and the other printReverse(char str[])
SetupReverse allocates memory for an user to enter a sentence. and printReverse takes that sentence and prints it in reverse. i.e. "C programming language is cool" becomes "cool is language programming C"
It was working until I decided to include a switch case statement in main to make it more interactive and now it doesn't even prompt me to enter the sentence, it skips it completely. Why?
Code:
#include <stdio.h>#include <string.h>
#include <ctype.h>
#include <stdlib.h>
/* Function that prints sentence in reverse
* 'Hello to the world' becomes
* 'world the to Hello'
* */
void dogcat();
/*Sets up the text that will be reversed*/
void SetupReverse();
/*Reverses the text that was typed in SetupReverse() function*/
void printReverse(char str[]);
/*Start
* of
* Main
* */
int main(int argc, char **argv)
{
int option;
printf("Please Select one of the following options: \n");
printf("1 Cats and Dogs\n");
printf("2 Reverse Text\n\n");
scanf("%d",&option);
while(1){
switch(option)
{
case 1:
dogcat();
break;
case 2:
SetupReverse();
break;
default:
printf("Invalid Option");
break;
}
printf("\n\nPlease Select one of the following options: \n");
printf("1 Cats and Dogs\n");
printf("2 Reverse Text\n");
scanf("%d",&option);
}
return 0;
}
/*End
* of
* Main
* */
void dogcat(){
int i;
int array[100];
for(i = 1; i <= 100; i++)
{
array[i] = i;
}
for(i = 1; i <= 100; i++)
{
if(array[i]%5 == 0 && array[i]%3 == 0){printf("dogcat ");}
else if(array[i]%3 == 0){printf("cat ");}
else if(array[i]%5 == 0){printf("dog ");}
else{printf("%d ",array[i]);}
}
}
void SetupReverse()
{
int size = 1;
char *str;
str = (char*) malloc(size*sizeof(char));
char c;
int t = 0;
int cnt = 0;
int len;
printf("Please input a sentence: \n");
c = getchar();
while(c!='\n') {
if(cnt > size) {
str = (char*) realloc(str,2*cnt);
}
str[t] = c;
c = getchar();
t++;
cnt++;
}
str[t]='\0';
printf("\nThe string is: \n %s \n",str);
len = strlen(str);
printf("\nThe size is: \n %d \n\n",len);
printf("\nThe string in Reverse is: \n \n");
printReverse(str);
printf("\n\n");
free(str);
}
void printReverse(char str[])
{
int length = strlen(str);
char newStr[length];
strcpy(newStr,str);
// Traverse string from end
int i;
for (i = length - 1; i >= 0; i--) {
if (newStr[i] == ' ') {
// putting the NULL character at the
// position of space characters for
// next iteration.
newStr[i] = '\0';
// Start from next charatcer
printf("%s ", &(newStr[i]) + 1);
}
}
// printing the last word
printf("%s", newStr);
}