End a While loop by entering a word in C

Viewed 69

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")
3 Answers

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)

As an added note, if you want to run this multiple times, reading in the first name and grade, then starting your loop doesn't make much sense. An "infinite loop" with a break if FINISH is entered makes more sense.

int main() {
    int score, count = 0;
    char name[10];

    while (1) {
        printf("please enter your name and score by order(enter FINISH in name to end)-->");
        scanf_s("%s%d", name, 10, &score);

        if (strcmp(name, "FINISH") == 0) break;

        // Do something with this data
    }

The objective seems to be: prompt, input, evaluate, do stuff (maybe)

int score, count = 0;
char name[10];

while( 1 ) {
    printf("please enter your name and score by order(enter FINISH in name to end)-->");
    scanf_s("%s%d", name, 10, &score);
    if ( strcmp( name, "FINISH" ) == 0 )
        break;
    // Do something with this data
}
// wrap things up
#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