سؤال

I'm a newbie on this. Can anyone help me to create this program? I got no idea how to make this program. Here's the description of the program.

created a program with the following features.

■ Function

enter the reference character string first.

Then, check if they match the criteria string

Counts the number of times if a match is found, and display

Display an error if it does not find a match.

And when we input string "end" the program will be closed.

■ Notes · use the function strlen First, and use function strcmp next.

■ run example (reference)

Please type the reference string: call

Please type [end] when you are finished.

call

Matched. Once

call

Matched. Twice

ccccccccccc

Input error

call

Matched. Three times

end

To exit

I have tried to make one and I made it like this

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

int main ()
{
    while(1000)
  {
  char call[]="call";
  char word[80];

     printf ("please type call: ");
     gets (word);

  if(strcmp(word,"call")==0)
  puts("matched!\n");
  else
  puts("error\n");
  }
  getch();
  return 0;
}
هل كانت مفيدة؟

المحلول

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

int main (void){
    char criteria[] = "call";
    char *mes[] = { "Many times", "Once", "Twice", "Three times" };
    char word[80];
    int match_count =0, not_end=1;

    do{
        printf(
            "Please type the reference string.\n"
            "Please type [end] when you are finished.\n"
            ">");
        fgets(word, sizeof(word), stdin);
        int len = strlen(word);
        if(word[len-1]=='\n')
            word[--len]='\0';
        if(strcmp(word, criteria)==0){
            if(++match_count > 3)
                printf("Matched. %s(%d)\n", *mes, match_count);
            else
                printf("Matched. %s\n", mes[match_count]);
        } else if(not_end=strcmp(word, "end"))
            printf("Input error\n");
    }while(not_end);
    printf("Bye!\n");
    return 0;
}

نصائح أخرى

Your first error is using strcmp() wrong. strcmp() has nothing to do with NULL. It returns a negative number, a positive one, or zero.

Also, your test for "wrong, please try again" makes no sense.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top