简体   繁体   中英

compare manually entered string with user entered

I try to read user input until user enters "End of story". I can successfully compare 2 user entered words via following code but I could not managed to compare user entered string with my string (in this case "test"). It keeps returning 0.

How should I compare them ?

I can't use string.h I'm preparing for an exam and string.h is forbidden to use.

int getLength(char str[]) {
  int i;
  for (i = 0; str[i] != '\0'; i++)
    ;
  return i - 1;
}

int strcompare(char alpha[], char bravo[]) {
  if (getLength(alpha) == getLength(bravo)) {

    int i;
    for (i = 0; i <= getLength(alpha); i++) {
      if (alpha[i] != bravo[i]) {
        return 0;
      }
    }
    return 1;    // theyre same
  } else {
    //different lengths cant be same
    return 0;    // not same
  }
  return -1;
}


char c[500], h[500] = { 't', 'e', 's', 't', '\0' };
gets(c);
printf("%d",strcompare(c,h));

The code you wrote has one extraneous part and a part which can't be reached, as well as suboptimal issues mentioned in the comments. The unreachable return -1 statement was probably intended to return -1 if sizes don't match.

#include <stdio.h>

int getLength(char str[])
{
  int i;
  for( i = 0 ; str[i] != '\0' ; i++ );
return i;
}

int strcompare(char alpha[], char bravo[]){
  int a = getLength(alpha);
  int b = getLength(bravo);
  if(a == b){
     int i;
     for( i = 0 ; i <= a ; i++ ){
         if(alpha[i] != bravo[i])
             return 0;   // sizes match, contents don't  
         }
   return 1;             // they're same
   }
return -1;               // sizes don't match
}


int main(void){        
  char c[500], h[500] = {'t','e','s','t','\0'};
  gets(c);
  printf("%d\n",strcompare(c,h));
return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM