Home > Software design >  End a While loop by entering a word in C
End a While loop by entering a word in C

Time:08-11

I want the loop to end when I type FINISH.

#include<stdio.h>

int main()
{
    int score,count=0;
    char name[10];
    printf("please enter your name and score by order(enter FINISH in name to end)-->");
    scanf_s("%s%d",name,10,&score);

    while (name!="FINISH")

CodePudding user response:

String comparisons don't work this way in C. Use the strcmp function from the string.h header. strcmp returns 0 to indicate equality.

while (strcmp(name, "FINISH") != 0)

CodePudding user response:

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

int main() {
  char name[10];
  int score, count = 0;
  printf("please enter your name and score by order(enter FINISH in name to end) --> ");
  scanf("%d %s", &score, name);
  
  // strcmp will return 0 if it is same and break a loop
  while (strcmp(name, "FINISH")) {
    printf("please enter your name and score by order(enter FINISH in name to end) --> ");
    scanf("%d %s", &score, name);
  }
}
  • Related