Home > OS >  How can I stop the input when I enter end
How can I stop the input when I enter end

Time:09-19

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;
}

CodePudding user response:

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("Is", 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("Is", str);
        reverse(str);

    }

    return 0;
}

and this is the output:

Enter string:abcd
 dcba
Enter string:end
 dne
Process finished with exit code 0
  •  Tags:  
  • c
  • Related