Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I stop the input when I enter end

got this little problem, I made this code for my task, it should input strings and print it in revese, the loop should end when you enter end, but it doesnt end, I know this is not how you check strings but I don’t know how to correct it. Thanks in advance for help.

#include <stdio.h>
#include <stdlib.h>


void reverse(char str[]){

    int length;
    for(length=strlen(str)-1; length >= 0; length--){
        printf("%c",str[length]);
    }
}

int main(void){

    char str[]="";

    while(str != "end"){

        printf("\nEnter string: ");
        scanf("%s", str);
        reverse(str);

    }

    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you have many problems in your code :

  1. when you write char str[]=""; this is will create a string of size = 1 only which will not accept any string you enter except for only one char , so you should do char str[50]; where 50 is the max expected length of the entered string.
  2. it’s not while(str != "end") it’s , while(strcmp(str,"end") != 0) as you want to compare the strings itself not addresses
  3. it’s better to write scanf("%49s", str); than scanf("%s", str); just to make sure that the entered string will always fit in your array
  4. in this line length = strlen(str)-1; , the strlen function return unsigned long long , so you should typecast that and write length = (int)strlen(str)-1; instead

with this all being said , this is the edited code :

#include <stdio.h>
#include <string.h>

void reverse(char str[]){

    int length;
    for(length = (int)strlen(str)-1; length >= 0; length--){
        printf("%c",str[length]);
    }
}

int main(void){

    char str[50];

    while(strcmp(str,"end") != 0){

        printf("\nEnter string: ");
        scanf("%49s", str);
        reverse(str);

    }

    return 0;
}

and this is the output:

Enter string:abcd
 dcba
Enter string:end
 dne
Process finished with exit code 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading