user3266210
user3266210

Reputation: 299

how to pass the value of a variable out from its loop in c

here i ask the user to input number:

do{
   printf("Enter cellphone number +63");
   fflush(stdin);
   gets(pb[i].cellphone);

 ///check if there is a similar number from the database
   for(r=0; r<i; r++){
      same = strcmp(pb[i].cellphone, pb[r].cellphone);
      if(same==0){
         printf("Number is same with contact no. %d\n", r+1);
       }
   }


 /// at this point the value of same is becoming nonzero and continues to the next code. 

}while(!isdigit(*pb[i].cellphone)||same == 0);

my goal is if the user input a non unique number it will ask gain the user to input a new number.

Upvotes: 2

Views: 1589

Answers (2)

perreal
perreal

Reputation: 97928

int find_num(char *phone, int i, phones *phones) {
  int r;
  for(r=0; r<i; r++){
      if (!strcmp(phone, pb[r].cellphone))
        return r;
  }
  return -1;
}

while (1) {
   printf("Enter cellphone number +63");
   fflush(stdin);
   gets(pb[i].cellphone);
   same = find_num(pb[i].cellphone, i, pb);
   if (same == -1) break;
   printf("Number is same with contact no. %d\n", same+1);        
}

Upvotes: 0

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

You need to exit the for loop or same will get overwritten in the next loop iteration:

do {
   printf("Enter cellphone number +63");
   fflush(stdout);     // Flush stdout so that text is shown (needed because the printf doesn't end with a newline and stdout is line buffered)
   gets(pb[i].cellphone);

 ///check if there is a similar number from the database
   for (r=0; r<i; r++){
      same = strcmp(pb[i].cellphone, pb[r].cellphone);
      if (same==0){
         printf("Number is same with contact no. %d\n", r+1);
         break;  // Exit the loop. Otherwise same will be overwritten in next iteration
      }
   }
} while(!isdigit(*pb[i].cellphone) || same == 0);

Upvotes: 1

Related Questions