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 :
- when you write
char str[]="";
this is will create a string ofsize = 1
only which will not accept any string you enter except for only onechar
, so you should dochar str[50];
where 50 is the max expected length of the entered string. - it's not
while(str != "end")
it's ,while(strcmp(str,"end") != 0)
as you want to compare the strings itself not addresses - it's better to write
scanf("Is", str);
thanscanf("%s", str);
just to make sure that the entered string will always fit in your array - in this line
length = strlen(str)-1;
, thestrlen
function returnunsigned long long
, so you should typecast that and writelength = (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